blob: 0fce4eb51c41923975266f9eb7a4973cd8c8f9f9 [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) {
501 case EventEntry::Type::FOCUS:
502 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
503 case EventEntry::Type::DRAG:
504 case EventEntry::Type::TOUCH_MODE_CHANGED:
505 case EventEntry::Type::SENSOR:
506 case EventEntry::Type::CONFIGURATION_CHANGED:
507 return false;
508 case EventEntry::Type::DEVICE_RESET:
509 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
Garfield Tan00f511d2019-06-12 16:55:40 -0700688InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800689 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
690
691InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
692 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 policy->getDispatcherConfiguration(&mConfig);
719}
720
721InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000722 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723
Prabir Pradhancef936d2021-07-21 16:17:52 +0000724 resetKeyRepeatLocked();
725 releasePendingEventLocked();
726 drainInboundQueueLocked();
727 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000729 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700730 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000731 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
733}
734
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700735status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700736 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700737 return ALREADY_EXISTS;
738 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700739 mThread = std::make_unique<InputThread>(
740 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
741 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700742}
743
744status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700745 if (mThread && mThread->isCallingThread()) {
746 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700747 return INVALID_OPERATION;
748 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700749 mThread.reset();
750 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700751}
752
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700754 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800756 std::scoped_lock _l(mLock);
757 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758
759 // Run a dispatch loop if there are no pending commands.
760 // The dispatch loop might enqueue commands to run afterwards.
761 if (!haveCommandsLocked()) {
762 dispatchOnceInnerLocked(&nextWakeupTime);
763 }
764
765 // Run all pending commands if there are any.
766 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000767 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700768 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800770
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700771 // If we are still waiting for ack on some events,
772 // we might have to wake up earlier to check if an app is anr'ing.
773 const nsecs_t nextAnrCheck = processAnrsLocked();
774 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
775
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800776 // We are about to enter an infinitely long sleep, because we have no commands or
777 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700778 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800779 mDispatcherEnteredIdle.notify_all();
780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 } // release lock
782
783 // Wait for callback or timeout or wake. (make sure we round up, not down)
784 nsecs_t currentTime = now();
785 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
786 mLooper->pollOnce(timeoutMillis);
787}
788
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700789/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500790 * Raise ANR if there is no focused window.
791 * Before the ANR is raised, do a final state check:
792 * 1. The currently focused application must be the same one we are waiting for.
793 * 2. Ensure we still don't have a focused window.
794 */
795void InputDispatcher::processNoFocusedWindowAnrLocked() {
796 // Check if the application that we are waiting for is still focused.
797 std::shared_ptr<InputApplicationHandle> focusedApplication =
798 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
799 if (focusedApplication == nullptr ||
800 focusedApplication->getApplicationToken() !=
801 mAwaitedFocusedApplication->getApplicationToken()) {
802 // Unexpected because we should have reset the ANR timer when focused application changed
803 ALOGE("Waited for a focused window, but focused application has already changed to %s",
804 focusedApplication->getName().c_str());
805 return; // The focused application has changed.
806 }
807
chaviw98318de2021-05-19 16:45:23 -0500808 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500809 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
810 if (focusedWindowHandle != nullptr) {
811 return; // We now have a focused window. No need for ANR.
812 }
813 onAnrLocked(mAwaitedFocusedApplication);
814}
815
816/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700817 * Check if any of the connections' wait queues have events that are too old.
818 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
819 * Return the time at which we should wake up next.
820 */
821nsecs_t InputDispatcher::processAnrsLocked() {
822 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700823 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700824 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
825 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
826 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500827 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700828 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500829 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700830 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700831 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500832 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700833 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
834 }
835 }
836
837 // Check if any connection ANRs are due
838 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
839 if (currentTime < nextAnrCheck) { // most likely scenario
840 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
841 }
842
843 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700844 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700845 if (connection == nullptr) {
846 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
847 return nextAnrCheck;
848 }
849 connection->responsive = false;
850 // Stop waking up for this unresponsive connection
851 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000852 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700853 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700854}
855
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800856std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700857 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800858 if (connection->monitor) {
859 return mMonitorDispatchingTimeout;
860 }
861 const sp<WindowInfoHandle> window =
862 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700863 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500864 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700865 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500866 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700867}
868
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
870 nsecs_t currentTime = now();
871
Jeff Browndc5992e2014-04-11 01:27:26 -0700872 // Reset the key repeat timer whenever normal dispatch is suspended while the
873 // device is in a non-interactive state. This is to ensure that we abort a key
874 // repeat if the device is just coming out of sleep.
875 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 resetKeyRepeatLocked();
877 }
878
879 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
880 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100881 if (DEBUG_FOCUS) {
882 ALOGD("Dispatch frozen. Waiting some more.");
883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 return;
885 }
886
887 // Optimize latency of app switches.
888 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
889 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
890 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
891 if (mAppSwitchDueTime < *nextWakeupTime) {
892 *nextWakeupTime = mAppSwitchDueTime;
893 }
894
895 // Ready to start a new event.
896 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700898 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 if (isAppSwitchDue) {
900 // The inbound queue is empty so the app switch key we were waiting
901 // for will never arrive. Stop waiting for it.
902 resetPendingAppSwitchLocked(false);
903 isAppSwitchDue = false;
904 }
905
906 // Synthesize a key repeat if appropriate.
907 if (mKeyRepeatState.lastKeyEntry) {
908 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
909 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
910 } else {
911 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
912 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
913 }
914 }
915 }
916
917 // Nothing to do if there is no pending event.
918 if (!mPendingEvent) {
919 return;
920 }
921 } else {
922 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700923 mPendingEvent = mInboundQueue.front();
924 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 traceInboundQueueLengthLocked();
926 }
927
928 // Poke user activity for this event.
929 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700930 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
933
934 // Now we have an event to dispatch.
935 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700936 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700938 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700940 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700942 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 }
944
945 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700946 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 }
948
949 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700950 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700951 const ConfigurationChangedEntry& typedEntry =
952 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700954 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 break;
956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700958 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700959 const DeviceResetEntry& typedEntry =
960 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700962 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 break;
964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100966 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 std::shared_ptr<FocusEntry> typedEntry =
968 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100969 dispatchFocusLocked(currentTime, typedEntry);
970 done = true;
971 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
972 break;
973 }
974
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700975 case EventEntry::Type::TOUCH_MODE_CHANGED: {
976 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
977 dispatchTouchModeChangeLocked(currentTime, typedEntry);
978 done = true;
979 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
980 break;
981 }
982
Prabir Pradhan99987712020-11-10 18:43:05 -0800983 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
984 const auto typedEntry =
985 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
986 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
987 done = true;
988 break;
989 }
990
arthurhungb89ccb02020-12-30 16:19:01 +0800991 case EventEntry::Type::DRAG: {
992 std::shared_ptr<DragEntry> typedEntry =
993 std::static_pointer_cast<DragEntry>(mPendingEvent);
994 dispatchDragLocked(currentTime, typedEntry);
995 done = true;
996 break;
997 }
998
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700999 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001000 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001002 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 resetPendingAppSwitchLocked(true);
1004 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 } else if (dropReason == DropReason::NOT_DROPPED) {
1006 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 }
1008 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001009 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001010 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001012 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1013 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001015 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 break;
1017 }
1018
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001019 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 std::shared_ptr<MotionEntry> motionEntry =
1021 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001022 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1023 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001026 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1029 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001031 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 }
Chris Yef59a2f42020-10-16 12:55:26 -07001034
1035 case EventEntry::Type::SENSOR: {
1036 std::shared_ptr<SensorEntry> sensorEntry =
1037 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1038 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1039 dropReason = DropReason::APP_SWITCH;
1040 }
1041 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1042 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1043 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1044 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1045 dropReason = DropReason::STALE;
1046 }
1047 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1048 done = true;
1049 break;
1050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052
1053 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001054 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001055 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Michael Wright3a981722015-06-10 15:26:13 +01001057 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058
1059 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001060 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 }
1062}
1063
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001064bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1065 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1066}
1067
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001068/**
1069 * Return true if the events preceding this incoming motion event should be dropped
1070 * Return false otherwise (the default behaviour)
1071 */
1072bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001073 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001074 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001075
1076 // Optimize case where the current application is unresponsive and the user
1077 // decides to touch a window in a different application.
1078 // If the application takes too long to catch up then we drop all events preceding
1079 // the touch into the other window.
1080 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001081 const int32_t displayId = motionEntry.displayId;
1082 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001083 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001084
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001085 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001086 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001087 touchedWindowHandle->getApplicationToken() !=
1088 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001089 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001090 ALOGI("Pruning input queue because user touched a different application while waiting "
1091 "for %s",
1092 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001093 return true;
1094 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001095
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001096 // Alternatively, maybe there's a spy window that could handle this event.
1097 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1098 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1099 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001100 const std::shared_ptr<Connection> connection =
1101 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001102 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001103 // This spy window could take more input. Drop all events preceding this
1104 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001105 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001106 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001107 mAwaitedFocusedApplication->getName().c_str());
1108 return true;
1109 }
1110 }
1111 }
1112
1113 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1114 // yet been processed by some connections, the dispatcher will wait for these motion
1115 // events to be processed before dispatching the key event. This is because these motion events
1116 // may cause a new window to be launched, which the user might expect to receive focus.
1117 // To prevent waiting forever for such events, just send the key to the currently focused window
1118 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1119 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1120 "just send the pending key event to the focused window.");
1121 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001122 }
1123 return false;
1124}
1125
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001126bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001127 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001128 mInboundQueue.push_back(std::move(newEntry));
1129 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 traceInboundQueueLengthLocked();
1131
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001132 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001134 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1135 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 // Optimize app switch latency.
1137 // If the application takes too long to catch up then we drop all events preceding
1138 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001139 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001141 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001143 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001145 if (DEBUG_APP_SWITCH) {
1146 ALOGD("App switch is pending!");
1147 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 mAppSwitchSawKeyDown = false;
1150 needWake = true;
1151 }
1152 }
1153 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001154
1155 // If a new up event comes in, and the pending event with same key code has been asked
1156 // to try again later because of the policy. We have to reset the intercept key wake up
1157 // time for it may have been handled in the policy and could be dropped.
1158 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1159 mPendingEvent->type == EventEntry::Type::KEY) {
1160 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1161 if (pendingKey.keyCode == keyEntry.keyCode &&
1162 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001163 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1164 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001165 pendingKey.interceptKeyWakeupTime = 0;
1166 needWake = true;
1167 }
1168 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 break;
1170 }
1171
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001172 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001173 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1174 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001175 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1176 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001177 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001181 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001182 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1183 break;
1184 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001185 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001186 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001187 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001188 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001189 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1190 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001191 // nothing to do
1192 break;
1193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195
1196 return needWake;
1197}
1198
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001200 // Do not store sensor event in recent queue to avoid flooding the queue.
1201 if (entry->type != EventEntry::Type::SENSOR) {
1202 mRecentQueue.push_back(entry);
1203 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001204 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001205 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207}
1208
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001209std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001210InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001211 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001213 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001214 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001215 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001216 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001217 continue;
1218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001220 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001221 if (!info.isSpy() &&
1222 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001223 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001224 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001225
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001226 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1227 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001228 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001229 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 }
1231 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001232 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Prabir Pradhand65552b2021-10-07 11:23:50 -07001235std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001236 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001237 // Traverse windows from front to back and gather the touched spy windows.
1238 std::vector<sp<WindowInfoHandle>> spyWindows;
1239 const auto& windowHandles = getWindowHandlesLocked(displayId);
1240 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1241 const WindowInfo& info = *windowHandle->getInfo();
1242
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001243 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001244 continue;
1245 }
1246 if (!info.isSpy()) {
1247 // The first touched non-spy window was found, so return the spy windows touched so far.
1248 return spyWindows;
1249 }
1250 spyWindows.push_back(windowHandle);
1251 }
1252 return spyWindows;
1253}
1254
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 const char* reason;
1257 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001258 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001259 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001260 ALOGD("Dropped event because policy consumed it.");
1261 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 reason = "inbound event was dropped because the policy consumed it";
1263 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001264 case DropReason::DISABLED:
1265 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001266 ALOGI("Dropped event because input dispatch is disabled.");
1267 }
1268 reason = "inbound event was dropped because input dispatch is disabled";
1269 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001270 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 ALOGI("Dropped event because of pending overdue app switch.");
1272 reason = "inbound event was dropped because of pending overdue app switch";
1273 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001274 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001275 ALOGI("Dropped event because the current application is not responding and the user "
1276 "has started interacting with a different application.");
1277 reason = "inbound event was dropped because the current application is not responding "
1278 "and the user has started interacting with a different application";
1279 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001280 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 ALOGI("Dropped event because it is stale.");
1282 reason = "inbound event was dropped because it is stale";
1283 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001284 case DropReason::NO_POINTER_CAPTURE:
1285 ALOGI("Dropped event because there is no window with Pointer Capture.");
1286 reason = "inbound event was dropped because there is no window with Pointer Capture";
1287 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001288 case DropReason::NOT_DROPPED: {
1289 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 }
1293
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001294 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001295 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001296 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001300 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001301 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1302 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001303 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 synthesizeCancelationEventsForAllConnectionsLocked(options);
1305 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001306 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1307 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 synthesizeCancelationEventsForAllConnectionsLocked(options);
1309 }
1310 break;
1311 }
Chris Yef59a2f42020-10-16 12:55:26 -07001312 case EventEntry::Type::SENSOR: {
1313 break;
1314 }
arthurhungb89ccb02020-12-30 16:19:01 +08001315 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1316 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001317 break;
1318 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001319 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001320 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001321 case EventEntry::Type::CONFIGURATION_CHANGED:
1322 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001323 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001324 break;
1325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
1327}
1328
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001329static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1331 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332}
1333
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001334bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1335 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1336 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1337 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338}
1339
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001340bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001341 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342}
1343
1344void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001345 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001347 if (DEBUG_APP_SWITCH) {
1348 if (handled) {
1349 ALOGD("App switch has arrived.");
1350 } else {
1351 ALOGD("App switch was abandoned.");
1352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354}
1355
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001357 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358}
1359
Prabir Pradhancef936d2021-07-21 16:17:52 +00001360bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001361 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 return false;
1363 }
1364
1365 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001366 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001367 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001368 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1369 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001370 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 return true;
1372}
1373
Prabir Pradhancef936d2021-07-21 16:17:52 +00001374void InputDispatcher::postCommandLocked(Command&& command) {
1375 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376}
1377
1378void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001379 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001381 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 releaseInboundEventLocked(entry);
1383 }
1384 traceInboundQueueLengthLocked();
1385}
1386
1387void InputDispatcher::releasePendingEventLocked() {
1388 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001390 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391 }
1392}
1393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001394void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001396 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001397 if (DEBUG_DISPATCH_CYCLE) {
1398 ALOGD("Injected inbound event was dropped.");
1399 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001400 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 }
1402 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001403 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 }
1405 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406}
1407
1408void InputDispatcher::resetKeyRepeatLocked() {
1409 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001410 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412}
1413
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001414std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1415 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416
Michael Wright2e732952014-09-24 13:26:59 -07001417 uint32_t policyFlags = entry->policyFlags &
1418 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001420 std::shared_ptr<KeyEntry> newEntry =
1421 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1422 entry->source, entry->displayId, policyFlags, entry->action,
1423 entry->flags, entry->keyCode, entry->scanCode,
1424 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426 newEntry->syntheticRepeat = true;
1427 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001429 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430}
1431
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001434 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1435 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437
1438 // Reset key repeating in case a keyboard device was added or removed or something.
1439 resetKeyRepeatLocked();
1440
1441 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001442 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1443 scoped_unlock unlock(mLock);
1444 mPolicy->notifyConfigurationChanged(eventTime);
1445 };
1446 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 return true;
1448}
1449
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001450bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1451 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001452 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1453 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1454 entry.deviceId);
1455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456
liushenxiang42232912021-05-21 20:24:09 +08001457 // Reset key repeating in case a keyboard device was disabled or enabled.
1458 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1459 resetKeyRepeatLocked();
1460 }
1461
Michael Wrightfb04fd52022-11-24 22:31:11 +00001462 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001463 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 synthesizeCancelationEventsForAllConnectionsLocked(options);
1465 return true;
1466}
1467
Vishnu Nairad321cd2020-08-20 16:40:21 -07001468void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001469 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001470 if (mPendingEvent != nullptr) {
1471 // Move the pending event to the front of the queue. This will give the chance
1472 // for the pending event to get dispatched to the newly focused window
1473 mInboundQueue.push_front(mPendingEvent);
1474 mPendingEvent = nullptr;
1475 }
1476
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001477 std::unique_ptr<FocusEntry> focusEntry =
1478 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1479 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001480
1481 // This event should go to the front of the queue, but behind all other focus events
1482 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001484 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001485 [](const std::shared_ptr<EventEntry>& event) {
1486 return event->type == EventEntry::Type::FOCUS;
1487 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001488
1489 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001490 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001491}
1492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001493void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001494 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001495 if (channel == nullptr) {
1496 return; // Window has gone away
1497 }
1498 InputTarget target;
1499 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001500 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001501 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001502 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1503 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001504 std::string reason = std::string("reason=").append(entry->reason);
1505 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001506 dispatchEventLocked(currentTime, entry, {target});
1507}
1508
Prabir Pradhan99987712020-11-10 18:43:05 -08001509void InputDispatcher::dispatchPointerCaptureChangedLocked(
1510 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1511 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001512 dropReason = DropReason::NOT_DROPPED;
1513
Prabir Pradhan99987712020-11-10 18:43:05 -08001514 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001515 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001516
1517 if (entry->pointerCaptureRequest.enable) {
1518 // Enable Pointer Capture.
1519 if (haveWindowWithPointerCapture &&
1520 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001521 // This can happen if pointer capture is disabled and re-enabled before we notify the
1522 // app of the state change, so there is no need to notify the app.
1523 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1524 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001525 }
1526 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001527 // This can happen if a window requests capture and immediately releases capture.
1528 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001529 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001530 return;
1531 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001532 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1533 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1534 return;
1535 }
1536
Vishnu Nairc519ff72021-01-21 08:23:08 -08001537 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001538 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1539 mWindowTokenWithPointerCapture = token;
1540 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001541 // Disable Pointer Capture.
1542 // We do not check if the sequence number matches for requests to disable Pointer Capture
1543 // for two reasons:
1544 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1545 // to disable capture with the same sequence number: one generated by
1546 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1547 // Capture being disabled in InputReader.
1548 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1549 // actual Pointer Capture state that affects events being generated by input devices is
1550 // in InputReader.
1551 if (!haveWindowWithPointerCapture) {
1552 // Pointer capture was already forcefully disabled because of focus change.
1553 dropReason = DropReason::NOT_DROPPED;
1554 return;
1555 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001556 token = mWindowTokenWithPointerCapture;
1557 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001558 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001559 setPointerCaptureLocked(false);
1560 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001561 }
1562
1563 auto channel = getInputChannelLocked(token);
1564 if (channel == nullptr) {
1565 // Window has gone away, clean up Pointer Capture state.
1566 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001567 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001568 setPointerCaptureLocked(false);
1569 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001570 return;
1571 }
1572 InputTarget target;
1573 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001574 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001575 entry->dispatchInProgress = true;
1576 dispatchEventLocked(currentTime, entry, {target});
1577
1578 dropReason = DropReason::NOT_DROPPED;
1579}
1580
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001581void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1582 const std::shared_ptr<TouchModeEntry>& entry) {
1583 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001584 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001585 if (windowHandles.empty()) {
1586 return;
1587 }
1588 const std::vector<InputTarget> inputTargets =
1589 getInputTargetsFromWindowHandlesLocked(windowHandles);
1590 if (inputTargets.empty()) {
1591 return;
1592 }
1593 entry->dispatchInProgress = true;
1594 dispatchEventLocked(currentTime, entry, inputTargets);
1595}
1596
1597std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1598 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1599 std::vector<InputTarget> inputTargets;
1600 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001601 const sp<IBinder>& token = handle->getToken();
1602 if (token == nullptr) {
1603 continue;
1604 }
1605 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1606 if (channel == nullptr) {
1607 continue; // Window has gone away
1608 }
1609 InputTarget target;
1610 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001611 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001612 inputTargets.push_back(target);
1613 }
1614 return inputTargets;
1615}
1616
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001617bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001620 if (!entry->dispatchInProgress) {
1621 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1622 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1623 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1624 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001625 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 // We have seen two identical key downs in a row which indicates that the device
1627 // driver is automatically generating key repeats itself. We take note of the
1628 // repeat here, but we disable our own next key repeat timer since it is clear that
1629 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001630 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1631 // Make sure we don't get key down from a different device. If a different
1632 // device Id has same key pressed down, the new device Id will replace the
1633 // current one to hold the key repeat with repeat count reset.
1634 // In the future when got a KEY_UP on the device id, drop it and do not
1635 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1637 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001638 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 } else {
1640 // Not a repeat. Save key down state in case we do see a repeat later.
1641 resetKeyRepeatLocked();
1642 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1643 }
1644 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001645 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1646 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001647 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001648 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001649 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1650 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001651 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 resetKeyRepeatLocked();
1653 }
1654
1655 if (entry->repeatCount == 1) {
1656 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1657 } else {
1658 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1659 }
1660
1661 entry->dispatchInProgress = true;
1662
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001663 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 }
1665
1666 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001667 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 if (currentTime < entry->interceptKeyWakeupTime) {
1669 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1670 *nextWakeupTime = entry->interceptKeyWakeupTime;
1671 }
1672 return false; // wait until next wakeup
1673 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001674 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 entry->interceptKeyWakeupTime = 0;
1676 }
1677
1678 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001679 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001681 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001682 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001683
1684 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1685 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1686 };
1687 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 return false; // wait for the command to run
1689 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001690 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001692 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001693 if (*dropReason == DropReason::NOT_DROPPED) {
1694 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 }
1696 }
1697
1698 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001699 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001700 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001701 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1702 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001703 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 return true;
1705 }
1706
1707 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001708 InputEventInjectionResult injectionResult;
1709 sp<WindowInfoHandle> focusedWindow =
1710 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1711 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001712 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 return false;
1714 }
1715
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001716 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 return true;
1719 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001720 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1721
1722 std::vector<InputTarget> inputTargets;
1723 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001724 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001725 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001727 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001728 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729
1730 // Dispatch the key.
1731 dispatchEventLocked(currentTime, entry, inputTargets);
1732 return true;
1733}
1734
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001736 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1737 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1738 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1739 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1740 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1741 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1742 entry.metaState, entry.repeatCount, entry.downTime);
1743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744}
1745
Prabir Pradhancef936d2021-07-21 16:17:52 +00001746void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1747 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001748 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001749 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1750 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1751 "source=0x%x, sensorType=%s",
1752 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001753 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001754 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001755 auto command = [this, entry]() REQUIRES(mLock) {
1756 scoped_unlock unlock(mLock);
1757
1758 if (entry->accuracyChanged) {
1759 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1760 }
1761 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1762 entry->hwTimestamp, entry->values);
1763 };
1764 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001765}
1766
1767bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001768 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1769 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001770 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 }
Chris Yef59a2f42020-10-16 12:55:26 -07001772 { // acquire lock
1773 std::scoped_lock _l(mLock);
1774
1775 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1776 std::shared_ptr<EventEntry> entry = *it;
1777 if (entry->type == EventEntry::Type::SENSOR) {
1778 it = mInboundQueue.erase(it);
1779 releaseInboundEventLocked(entry);
1780 }
1781 }
1782 }
1783 return true;
1784}
1785
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001786bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001788 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001790 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 entry->dispatchInProgress = true;
1792
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795
1796 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001797 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001798 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1800 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 return true;
1802 }
1803
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001804 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805
1806 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001807 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
1809 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 if (isPointerEvent) {
1812 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001813
1814 if (mDragState &&
1815 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1816 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1817 pilferPointersLocked(mDragState->dragWindow->getToken());
1818 }
1819
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001820 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001821 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001822 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001823 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1824 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 } else {
1826 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001827 sp<WindowInfoHandle> focusedWindow =
1828 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1829 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1830 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1831 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001832 InputTarget::Flags::FOREGROUND |
1833 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001834 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 return false;
1839 }
1840
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001841 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001842 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001843 return true;
1844 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001846 CancelationOptions::Mode mode(
1847 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1848 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001849 CancelationOptions options(mode, "input event injection failed");
1850 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 return true;
1852 }
1853
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001854 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001855 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
1857 // Dispatch the motion.
1858 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001859 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001860 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 synthesizeCancelationEventsForAllConnectionsLocked(options);
1862 }
1863 dispatchEventLocked(currentTime, entry, inputTargets);
1864 return true;
1865}
1866
chaviw98318de2021-05-19 16:45:23 -05001867void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001868 bool isExiting, const int32_t rawX,
1869 const int32_t rawY) {
1870 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001871 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001872 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1873 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001874
1875 enqueueInboundEventLocked(std::move(dragEntry));
1876}
1877
1878void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1879 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1880 if (channel == nullptr) {
1881 return; // Window has gone away
1882 }
1883 InputTarget target;
1884 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001885 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001886 entry->dispatchInProgress = true;
1887 dispatchEventLocked(currentTime, entry, {target});
1888}
1889
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001890void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001891 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001892 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001893 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001894 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001895 "metaState=0x%x, buttonState=0x%x,"
1896 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001897 prefix, entry.eventTime, entry.deviceId,
1898 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1899 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1900 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1901 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001903 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001904 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001905 "x=%f, y=%f, pressure=%f, size=%f, "
1906 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1907 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001908 i, entry.pointerProperties[i].id,
1909 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001910 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1911 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1912 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1913 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1914 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1915 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1916 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1917 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1918 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921}
1922
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001923void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1924 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001925 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001926 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001927 if (DEBUG_DISPATCH_CYCLE) {
1928 ALOGD("dispatchEventToCurrentInputTargets");
1929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001931 updateInteractionTokensLocked(*eventEntry, inputTargets);
1932
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1934
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001935 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001937 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001938 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001939 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001940 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001941 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001943 if (DEBUG_FOCUS) {
1944 ALOGD("Dropping event delivery to target with channel '%s' because it "
1945 "is no longer registered with the input dispatcher.",
1946 inputTarget.inputChannel->getName().c_str());
1947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 }
1949 }
1950}
1951
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001952void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001953 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1954 // If the policy decides to close the app, we will get a channel removal event via
1955 // unregisterInputChannel, and will clean up the connection that way. We are already not
1956 // sending new pointers to the connection when it blocked, but focused events will continue to
1957 // pile up.
1958 ALOGW("Canceling events for %s because it is unresponsive",
1959 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001960 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001961 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 "application not responding");
1963 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965}
1966
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001968 if (DEBUG_FOCUS) {
1969 ALOGD("Resetting ANR timeouts.");
1970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
1972 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001973 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001974 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975}
1976
Tiger Huang721e26f2018-07-24 22:26:19 +08001977/**
1978 * Get the display id that the given event should go to. If this event specifies a valid display id,
1979 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1980 * Focused display is the display that the user most recently interacted with.
1981 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001982int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001983 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001984 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001985 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1987 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001988 break;
1989 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001990 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001991 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1992 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 break;
1994 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001995 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001996 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001997 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001998 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001999 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002000 case EventEntry::Type::SENSOR:
2001 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002002 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 return ADISPLAY_ID_NONE;
2004 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002005 }
2006 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2007}
2008
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002009bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2010 const char* focusedWindowName) {
2011 if (mAnrTracker.empty()) {
2012 // already processed all events that we waited for
2013 mKeyIsWaitingForEventsTimeout = std::nullopt;
2014 return false;
2015 }
2016
2017 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2018 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002019 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002020 mKeyIsWaitingForEventsTimeout = currentTime +
2021 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2022 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 return true;
2024 }
2025
2026 // We still have pending events, and already started the timer
2027 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2028 return true; // Still waiting
2029 }
2030
2031 // Waited too long, and some connection still hasn't processed all motions
2032 // Just send the key to the focused window
2033 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2034 focusedWindowName);
2035 mKeyIsWaitingForEventsTimeout = std::nullopt;
2036 return false;
2037}
2038
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002039sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2040 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2041 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002042 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002043 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044
Tiger Huang721e26f2018-07-24 22:26:19 +08002045 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002046 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002047 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002048 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2049
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 // If there is no currently focused window and no focused application
2051 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2053 ALOGI("Dropping %s event because there is no focused window or focused application in "
2054 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002055 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002056 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058
Vishnu Nair062a8672021-09-03 16:07:44 -07002059 // Drop key events if requested by input feature
2060 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002061 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002062 }
2063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2065 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2066 // start interacting with another application via touch (app switch). This code can be removed
2067 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2068 // an app is expected to have a focused window.
2069 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2070 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2071 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002072 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2073 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2074 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002076 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002077 ALOGW("Waiting because no window has focus but %s may eventually add a "
2078 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002079 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002080 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002081 outInjectionResult = InputEventInjectionResult::PENDING;
2082 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002083 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2084 // Already raised ANR. Drop the event
2085 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002086 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002087 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002088 } else {
2089 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002090 outInjectionResult = InputEventInjectionResult::PENDING;
2091 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 }
2093 }
2094
2095 // we have a valid, non-null focused window
2096 resetNoFocusedWindowTimeoutLocked();
2097
Prabir Pradhan5735a322022-04-11 17:23:34 +00002098 // Verify targeted injection.
2099 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2100 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002101 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2102 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
2104
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002105 if (focusedWindowHandle->getInfo()->inputConfig.test(
2106 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002108 outInjectionResult = InputEventInjectionResult::PENDING;
2109 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 }
2111
2112 // If the event is a key event, then we must wait for all previous events to
2113 // complete before delivering it because previous events may have the
2114 // side-effect of transferring focus to a different window and we want to
2115 // ensure that the following keys are sent to the new window.
2116 //
2117 // Suppose the user touches a button in a window then immediately presses "A".
2118 // If the button causes a pop-up window to appear then we want to ensure that
2119 // the "A" key is delivered to the new pop-up window. This is because users
2120 // often anticipate pending UI changes when typing on a keyboard.
2121 // To obtain this behavior, we must serialize key events with respect to all
2122 // prior input events.
2123 if (entry.type == EventEntry::Type::KEY) {
2124 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2125 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002126 outInjectionResult = InputEventInjectionResult::PENDING;
2127 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002131 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2132 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133}
2134
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002135/**
2136 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2137 * that are currently unresponsive.
2138 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002139std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2140 const std::vector<Monitor>& monitors) const {
2141 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002142 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002143 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002144 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002145 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002146 if (connection == nullptr) {
2147 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002148 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002149 return false;
2150 }
2151 if (!connection->responsive) {
2152 ALOGW("Unresponsive monitor %s will not get the new gesture",
2153 connection->inputChannel->getName().c_str());
2154 return false;
2155 }
2156 return true;
2157 });
2158 return responsiveMonitors;
2159}
2160
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002161/**
2162 * In general, touch should be always split between windows. Some exceptions:
2163 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2164 * from the same device, *and* the window that's receiving the current pointer does not support
2165 * split touch.
2166 * 2. Don't split mouse events
2167 */
2168bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2169 const MotionEntry& entry) const {
2170 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2171 // We should never split mouse events
2172 return false;
2173 }
2174 for (const TouchedWindow& touchedWindow : touchState.windows) {
2175 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2176 // Spy windows should not affect whether or not touch is split.
2177 continue;
2178 }
2179 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2180 continue;
2181 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002182 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2183 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2184 // Wallpaper window should not affect whether or not touch is split
2185 continue;
2186 }
2187
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002188 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2189 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002190 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002191 return false;
2192 }
2193 }
2194 return true;
2195}
2196
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002197std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002198 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2199 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002200 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002202 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 // For security reasons, we defer updating the touch state until we are sure that
2204 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002205 const int32_t displayId = entry.displayId;
2206 const int32_t action = entry.action;
2207 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208
2209 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002210 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 // Copy current touch state into tempTouchState.
2213 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2214 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002215 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002216 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002217 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2218 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002219 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002220 }
2221
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002222 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002223 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002224 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002225
2226 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2227 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2228 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002229 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2230 // touchable windows.
2231 const bool wasDown = oldState != nullptr && oldState->isDown();
2232 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2233 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2234 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002235 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002236
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002237 // If pointers are already down, let's finish the current gesture and ignore the new events
2238 // from another device. However, if the new event is a down event, let's cancel the current
2239 // touch and let the new one take over.
2240 if (switchedDevice && wasDown && !isDown) {
2241 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2242 << " is already down in display " << displayId << ": " << entry.getDescription();
2243 // TODO(b/211379801): test multiple simultaneous input streams.
2244 outInjectionResult = InputEventInjectionResult::FAILED;
2245 return {}; // wrong device
2246 }
2247
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002249 // If a new gesture is starting, clear the touch state completely.
2250 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 tempTouchState.deviceId = entry.deviceId;
2252 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002254 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002255 ALOGI("Dropping move event because a pointer for a different device is already active "
2256 "in display %" PRId32,
2257 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002258 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002259 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002260 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
2262
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002263 if (isHoverAction) {
2264 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2265 // all of the existing hovering pointers and recompute.
2266 tempTouchState.clearHoveringPointers();
2267 }
2268
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2270 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002271 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002272 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002273 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2274 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002275 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002276 auto [newTouchedWindowHandle, outsideTargets] =
2277 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002278
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002279 if (isDown) {
2280 targets += outsideTargets;
2281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002283 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002284 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002286 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002287 }
2288
Prabir Pradhan5735a322022-04-11 17:23:34 +00002289 // Verify targeted injection.
2290 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2291 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002292 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002293 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002294 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002295 }
2296
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002297 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002298 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002299 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2300 // New window supports splitting, but we should never split mouse events.
2301 isSplit = !isFromMouse;
2302 } else if (isSplit) {
2303 // New window does not support splitting but we have already split events.
2304 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002305 newTouchedWindowHandle = nullptr;
2306 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 } else {
2308 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002309 // be delivered to a new window which supports split touch. Pointers from a mouse device
2310 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002311 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002312 }
2313
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002314 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002315 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002316 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002317 // Process the foreground window first so that it is the first to receive the event.
2318 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002319 }
2320
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002321 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002322 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2323 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002324 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002325 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002326 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002327 }
2328
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002330 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002331 continue;
2332 }
2333
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002334 if (isHoverAction) {
2335 const int32_t pointerId = entry.pointerProperties[0].id;
2336 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2337 // Pointer left. Remove it
2338 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2339 } else {
2340 // The "windowHandle" is the target of this hovering pointer.
2341 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2342 pointerId);
2343 }
2344 }
2345
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002346 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002347 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002348
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002349 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2350 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002351 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002352 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353
2354 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002355 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 }
2357 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002358 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002359 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002360 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002361 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002362
2363 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002364 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002365 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002366 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002367 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002369 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2370 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2371
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002372 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2373 // still add a window to the touch state. We should avoid doing that, but some of the
2374 // later checks ("at least one foreground window") rely on this in order to dispatch
2375 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002376 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002377 isDownOrPointerDown
2378 ? std::make_optional(entry.eventTime)
2379 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002380
2381 // If this is the pointer going down and the touched window has a wallpaper
2382 // then also add the touched wallpaper windows so they are locked in for the duration
2383 // of the touch gesture.
2384 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2385 // engine only supports touch events. We would need to add a mechanism similar
2386 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002387 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002388 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2389 windowHandle->getInfo()->inputConfig.test(
2390 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2391 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2392 if (wallpaper != nullptr) {
2393 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2394 InputTarget::Flags::WINDOW_IS_OBSCURED |
2395 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2396 InputTarget::Flags::DISPATCH_AS_IS;
2397 if (isSplit) {
2398 wallpaperFlags |= InputTarget::Flags::SPLIT;
2399 }
2400 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2401 entry.eventTime);
2402 }
2403 }
2404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002406
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002407 // If a window is already pilfering some pointers, give it this new pointer as well and
2408 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2409 // which is a specific behaviour that we want.
2410 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2411 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002412 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002413 touchedWindow.pilferedPointerIds.count() > 0) {
2414 // This window is already pilfering some pointers, and this new pointer is also
2415 // going to it. Therefore, take over this pointer and don't give it to anyone
2416 // else.
2417 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002418 }
2419 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002420
2421 // Restrict all pilfered pointers to the pilfering windows.
2422 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 } else {
2424 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2425
2426 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002427 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002428 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2429 "dropped the pointer down event in display "
2430 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002431 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002432 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434
arthurhung6d4bed92021-03-17 11:59:33 +08002435 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002436
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002438 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002439 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002440 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002441 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002442 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002443 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002444 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002445 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002446
Prabir Pradhan5735a322022-04-11 17:23:34 +00002447 // Verify targeted injection.
2448 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2449 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002450 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002451 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002452 }
2453
Vishnu Nair062a8672021-09-03 16:07:44 -07002454 // Drop touch events if requested by input feature
2455 if (newTouchedWindowHandle != nullptr &&
2456 shouldDropInput(entry, newTouchedWindowHandle)) {
2457 newTouchedWindowHandle = nullptr;
2458 }
2459
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002460 if (!haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
2461 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2462 oldTouchedWindowHandle->getName().c_str(),
2463 newTouchedWindowHandle->getName().c_str(), displayId);
2464
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002466 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002467 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002468 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002469
2470 const TouchedWindow& touchedWindow =
2471 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2472 addWindowTargetLocked(oldTouchedWindowHandle,
2473 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2474 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475
2476 // Make a slippery entrance into the new window.
2477 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002478 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002481 ftl::Flags<InputTarget::Flags> targetFlags =
2482 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002483 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002484 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002487 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
2489 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002490 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002491 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002492 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 }
2494
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002495 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2496 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002497
2498 // Check if the wallpaper window should deliver the corresponding event.
2499 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002500 tempTouchState, pointerId, targets);
2501 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 }
2503 }
Arthur Hung96483742022-11-15 03:30:48 +00002504
2505 // Update the pointerIds for non-splittable when it received pointer down.
2506 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2507 // If no split, we suppose all touched windows should receive pointer down.
2508 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2509 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2510 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2511 // Ignore drag window for it should just track one pointer.
2512 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2513 continue;
2514 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002515 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002516 }
2517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 }
2519
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002520 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002521 {
2522 std::vector<TouchedWindow> hoveringWindows =
2523 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2524 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2525 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2526 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2527 targets);
2528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002530 // Ensure that we have at least one foreground window or at least one window that cannot be a
2531 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2532 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2533 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002534 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2535 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002536 return !canReceiveForegroundTouches(
2537 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002538 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002539 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002540 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2541 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002542 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002543 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
2545
Prabir Pradhan5735a322022-04-11 17:23:34 +00002546 // Ensure that all touched windows are valid for injection.
2547 if (entry.injectionState != nullptr) {
2548 std::string errs;
2549 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002550 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002551 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2552 // dispatched to any uid, since the coords will be zeroed out later.
2553 continue;
2554 }
2555 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2556 if (err) errs += "\n - " + *err;
2557 }
2558 if (!errs.empty()) {
2559 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2560 "%d:%s",
2561 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002562 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002563 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002564 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002565 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002566
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002567 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2568 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002570 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002571 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002572 if (foregroundWindowHandle) {
2573 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002574 for (InputTarget& target : targets) {
2575 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2576 sp<WindowInfoHandle> targetWindow =
2577 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2578 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2579 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582 }
2583 }
2584 }
2585
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002586 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002587 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002588 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002589 // Windows with hovering pointers are getting persisted inside TouchState.
2590 // Do not send this event to those windows.
2591 continue;
2592 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002593 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2594 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2595 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002596 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002597
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002598 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002599 // Drop the outside or hover touch windows since we will not care about them
2600 // in the next iteration.
2601 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002604 if (switchedDevice) {
2605 if (DEBUG_FOCUS) {
2606 ALOGD("Conflicting pointer actions: Switched to a different device.");
2607 }
2608 *outConflictingPointerActions = true;
2609 }
2610
2611 if (isHoverAction) {
2612 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002613 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002614 ALOGD_IF(DEBUG_FOCUS,
2615 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002616 *outConflictingPointerActions = true;
2617 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002618 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2619 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2620 tempTouchState.deviceId = entry.deviceId;
2621 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002622 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002623 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2624 // Pointer went up.
2625 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002626 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002627 // All pointers up or canceled.
2628 tempTouchState.reset();
2629 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2630 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002631 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2632 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002633 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002634 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002635 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2636 // One pointer went up.
2637 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2638 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002640 for (size_t i = 0; i < tempTouchState.windows.size();) {
2641 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002642 touchedWindow.pointerIds.reset(pointerId);
2643 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002644 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2645 continue;
2646 }
2647 i += 1;
2648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002651 // Save changes unless the action was scroll in which case the temporary touch
2652 // state was only valid for this one action.
2653 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002654 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002655 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002656 mTouchStatesByDisplay[displayId] = tempTouchState;
2657 } else {
2658 mTouchStatesByDisplay.erase(displayId);
2659 }
2660 }
2661
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002662 if (tempTouchState.windows.empty()) {
2663 mTouchStatesByDisplay.erase(displayId);
2664 }
2665
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002666 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667}
2668
arthurhung6d4bed92021-03-17 11:59:33 +08002669void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002670 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2671 // have an explicit reason to support it.
2672 constexpr bool isStylus = false;
2673
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002674 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002675 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002676 if (dropWindow) {
2677 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002678 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002679 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002680 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002681 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002682 }
2683 mDragState.reset();
2684}
2685
2686void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002687 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002688 return;
2689 }
2690
arthurhung6d4bed92021-03-17 11:59:33 +08002691 if (!mDragState->isStartDrag) {
2692 mDragState->isStartDrag = true;
2693 mDragState->isStylusButtonDownAtStart =
2694 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2695 }
2696
Arthur Hung54745652022-04-20 07:17:41 +00002697 // Find the pointer index by id.
2698 int32_t pointerIndex = 0;
2699 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2700 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2701 if (pointerProperties.id == mDragState->pointerId) {
2702 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002703 }
Arthur Hung54745652022-04-20 07:17:41 +00002704 }
arthurhung6d4bed92021-03-17 11:59:33 +08002705
Arthur Hung54745652022-04-20 07:17:41 +00002706 if (uint32_t(pointerIndex) == entry.pointerCount) {
2707 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002708 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002709 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002710 return;
2711 }
2712
2713 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2714 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2715 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2716
2717 switch (maskedAction) {
2718 case AMOTION_EVENT_ACTION_MOVE: {
2719 // Handle the special case : stylus button no longer pressed.
2720 bool isStylusButtonDown =
2721 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2722 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2723 finishDragAndDrop(entry.displayId, x, y);
2724 return;
2725 }
2726
2727 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2728 // until we have an explicit reason to support it.
2729 constexpr bool isStylus = false;
2730
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002731 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002732 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002733 // enqueue drag exit if needed.
2734 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2735 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2736 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002737 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002738 y);
2739 }
2740 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2741 }
2742 // enqueue drag location if needed.
2743 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002744 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002745 }
2746 break;
2747 }
2748
2749 case AMOTION_EVENT_ACTION_POINTER_UP:
2750 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2751 break;
2752 }
2753 // The drag pointer is up.
2754 [[fallthrough]];
2755 case AMOTION_EVENT_ACTION_UP:
2756 finishDragAndDrop(entry.displayId, x, y);
2757 break;
2758 case AMOTION_EVENT_ACTION_CANCEL: {
2759 ALOGD("Receiving cancel when drag and drop.");
2760 sendDropWindowCommandLocked(nullptr, 0, 0);
2761 mDragState.reset();
2762 break;
2763 }
arthurhungb89ccb02020-12-30 16:19:01 +08002764 }
2765}
2766
chaviw98318de2021-05-19 16:45:23 -05002767void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002768 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002769 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002770 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002771 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002772 std::vector<InputTarget>::iterator it =
2773 std::find_if(inputTargets.begin(), inputTargets.end(),
2774 [&windowHandle](const InputTarget& inputTarget) {
2775 return inputTarget.inputChannel->getConnectionToken() ==
2776 windowHandle->getToken();
2777 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002778
chaviw98318de2021-05-19 16:45:23 -05002779 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002780
2781 if (it == inputTargets.end()) {
2782 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002783 std::shared_ptr<InputChannel> inputChannel =
2784 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002785 if (inputChannel == nullptr) {
2786 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2787 return;
2788 }
2789 inputTarget.inputChannel = inputChannel;
2790 inputTarget.flags = targetFlags;
2791 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002792 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002793 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2794 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002795 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002796 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002797 // DisplayInfo not found for this window on display windowInfo->displayId.
2798 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002799 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002800 inputTargets.push_back(inputTarget);
2801 it = inputTargets.end() - 1;
2802 }
2803
2804 ALOG_ASSERT(it->flags == targetFlags);
2805 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2806
chaviw1ff3d1e2020-07-01 15:53:47 -07002807 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808}
2809
Michael Wright3dd60e22019-03-27 22:06:44 +00002810void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002811 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002812 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2813 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002814
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002815 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2816 InputTarget target;
2817 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002818 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002819 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2820 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002821 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2822 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002823 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002824 target.setDefaultPointerTransform(target.displayTransform);
2825 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 }
2827}
2828
Robert Carrc9bf1d32020-04-13 17:21:08 -07002829/**
2830 * Indicate whether one window handle should be considered as obscuring
2831 * another window handle. We only check a few preconditions. Actually
2832 * checking the bounds is left to the caller.
2833 */
chaviw98318de2021-05-19 16:45:23 -05002834static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2835 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002836 // Compare by token so cloned layers aren't counted
2837 if (haveSameToken(windowHandle, otherHandle)) {
2838 return false;
2839 }
2840 auto info = windowHandle->getInfo();
2841 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002842 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002843 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002844 } else if (otherInfo->alpha == 0 &&
2845 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002846 // Those act as if they were invisible, so we don't need to flag them.
2847 // We do want to potentially flag touchable windows even if they have 0
2848 // opacity, since they can consume touches and alter the effects of the
2849 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002850 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002851 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2852 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002853 } else if (info->ownerUid == otherInfo->ownerUid) {
2854 // If ownerUid is the same we don't generate occlusion events as there
2855 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002856 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002857 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002858 return false;
2859 } else if (otherInfo->displayId != info->displayId) {
2860 return false;
2861 }
2862 return true;
2863}
2864
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002865/**
2866 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2867 * untrusted, one should check:
2868 *
2869 * 1. If result.hasBlockingOcclusion is true.
2870 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2871 * BLOCK_UNTRUSTED.
2872 *
2873 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2874 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2875 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2876 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2877 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2878 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2879 *
2880 * If neither of those is true, then it means the touch can be allowed.
2881 */
2882InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002883 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2884 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002885 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002886 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002887 TouchOcclusionInfo info;
2888 info.hasBlockingOcclusion = false;
2889 info.obscuringOpacity = 0;
2890 info.obscuringUid = -1;
2891 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002892 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002893 if (windowHandle == otherHandle) {
2894 break; // All future windows are below us. Exit early.
2895 }
chaviw98318de2021-05-19 16:45:23 -05002896 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002897 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2898 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002899 if (DEBUG_TOUCH_OCCLUSION) {
2900 info.debugInfo.push_back(
2901 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2902 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002903 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2904 // we perform the checks below to see if the touch can be propagated or not based on the
2905 // window's touch occlusion mode
2906 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2907 info.hasBlockingOcclusion = true;
2908 info.obscuringUid = otherInfo->ownerUid;
2909 info.obscuringPackage = otherInfo->packageName;
2910 break;
2911 }
2912 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2913 uint32_t uid = otherInfo->ownerUid;
2914 float opacity =
2915 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2916 // Given windows A and B:
2917 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2918 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2919 opacityByUid[uid] = opacity;
2920 if (opacity > info.obscuringOpacity) {
2921 info.obscuringOpacity = opacity;
2922 info.obscuringUid = uid;
2923 info.obscuringPackage = otherInfo->packageName;
2924 }
2925 }
2926 }
2927 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002928 if (DEBUG_TOUCH_OCCLUSION) {
2929 info.debugInfo.push_back(
2930 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2931 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002932 return info;
2933}
2934
chaviw98318de2021-05-19 16:45:23 -05002935std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002936 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002937 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2938 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2939 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2940 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002941 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2942 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2943 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2944 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2945 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002946 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002947 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002948}
2949
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002950bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2951 if (occlusionInfo.hasBlockingOcclusion) {
2952 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2953 occlusionInfo.obscuringUid);
2954 return false;
2955 }
2956 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2957 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2958 "%.2f, maximum allowed = %.2f)",
2959 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2960 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2961 return false;
2962 }
2963 return true;
2964}
2965
chaviw98318de2021-05-19 16:45:23 -05002966bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002969 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2970 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002971 if (windowHandle == otherHandle) {
2972 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
chaviw98318de2021-05-19 16:45:23 -05002974 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002975 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002976 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 return true;
2978 }
2979 }
2980 return false;
2981}
2982
chaviw98318de2021-05-19 16:45:23 -05002983bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002984 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002985 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2986 const WindowInfo* windowInfo = windowHandle->getInfo();
2987 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002988 if (windowHandle == otherHandle) {
2989 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002990 }
chaviw98318de2021-05-19 16:45:23 -05002991 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002992 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002993 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002994 return true;
2995 }
2996 }
2997 return false;
2998}
2999
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003000std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003001 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003002 if (applicationHandle != nullptr) {
3003 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003004 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 } else {
3006 return applicationHandle->getName();
3007 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003008 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003009 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003011 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 }
3013}
3014
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003015void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003016 if (!isUserActivityEvent(eventEntry)) {
3017 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003018 return;
3019 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003020 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003021 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08003022 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003023 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003024 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003025 if (DEBUG_DISPATCH_CYCLE) {
3026 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
3027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 return;
3029 }
3030 }
3031
3032 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003033 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003034 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003035 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3036 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 return;
3038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 eventType = USER_ACTIVITY_EVENT_TOUCH;
3042 }
3043 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003045 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003046 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3047 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 return;
3049 }
3050 eventType = USER_ACTIVITY_EVENT_BUTTON;
3051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003053 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003054 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003055 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003056 break;
3057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
3059
Prabir Pradhancef936d2021-07-21 16:17:52 +00003060 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3061 REQUIRES(mLock) {
3062 scoped_unlock unlock(mLock);
3063 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3064 };
3065 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066}
3067
3068void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003069 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003070 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003071 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003072 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003074 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003075 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003076 ATRACE_NAME(message.c_str());
3077 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003078 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003079 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003080 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003081 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003082 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003083 inputTarget.getPointerInfoString().c_str());
3084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
3086 // Skip this event if the connection status is not normal.
3087 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003088 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003089 if (DEBUG_DISPATCH_CYCLE) {
3090 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003091 connection->getInputChannelName().c_str(),
3092 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 return;
3095 }
3096
3097 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003098 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003099 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003100 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003101 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003103 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003104 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003105 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3106 logDispatchStateLocked();
3107 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3108 "target on connection "
3109 << connection->getInputChannelName() << " for "
3110 << originalMotionEntry.getDescription();
3111 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003113 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3114 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 if (!splitMotionEntry) {
3116 return; // split event was dropped
3117 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003118 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3119 std::string reason = std::string("reason=pointer cancel on split window");
3120 android_log_event_list(LOGTAG_INPUT_CANCEL)
3121 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3122 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003123 if (DEBUG_FOCUS) {
3124 ALOGD("channel '%s' ~ Split motion event.",
3125 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003126 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003127 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3129 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 return;
3131 }
3132 }
3133
3134 // Not splitting. Enqueue dispatch entries for the event as is.
3135 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3136}
3137
3138void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003139 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003140 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003141 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003142 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003144 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003145 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003146 ATRACE_NAME(message.c_str());
3147 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003148 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3149 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003150
hongzuo liu95785e22022-09-06 02:51:35 +00003151 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152
3153 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003154 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003155 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003156 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003157 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003158 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003159 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003160 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003161 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003162 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003163 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003164 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003165 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
3167 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003168 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 startDispatchCycleLocked(currentTime, connection);
3170 }
3171}
3172
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003173void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003174 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003175 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003176 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003177 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3179 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003180 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003181 ATRACE_NAME(message.c_str());
3182 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003183 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3184 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 return;
3186 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003187
3188 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3189 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190
3191 // This is a new event.
3192 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003193 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003194 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003196 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3197 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003198 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003200 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003201 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003202 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003203 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 dispatchEntry->resolvedAction = keyEntry.action;
3205 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3208 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003209 if (DEBUG_DISPATCH_CYCLE) {
3210 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3211 "event",
3212 connection->getInputChannelName().c_str());
3213 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214 return; // skip the inconsistent event
3215 }
3216 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003219 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003221 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3222 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3223 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3224 static_cast<int32_t>(IdGenerator::Source::OTHER);
3225 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003226 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003227 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003228 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003230 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003232 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003234 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3236 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003237 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003238 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 }
3240 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003241 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3242 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003243 if (DEBUG_DISPATCH_CYCLE) {
3244 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3245 "enter event",
3246 connection->getInputChannelName().c_str());
3247 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003248 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3249 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003253 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003254 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3255 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3256 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003257 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3259 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003260 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3265 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003266 if (DEBUG_DISPATCH_CYCLE) {
3267 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3268 "event",
3269 connection->getInputChannelName().c_str());
3270 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 return; // skip the inconsistent event
3272 }
3273
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003274 dispatchEntry->resolvedEventId =
3275 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3276 ? mIdGenerator.nextId()
3277 : motionEntry.id;
3278 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3279 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3280 ") to MotionEvent(id=0x%" PRIx32 ").",
3281 motionEntry.id, dispatchEntry->resolvedEventId);
3282 ATRACE_NAME(message.c_str());
3283 }
3284
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003285 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3286 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3287 // Skip reporting pointer down outside focus to the policy.
3288 break;
3289 }
3290
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003291 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003292 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293
3294 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003296 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003297 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003298 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3299 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003300 break;
3301 }
Chris Yef59a2f42020-10-16 12:55:26 -07003302 case EventEntry::Type::SENSOR: {
3303 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3304 break;
3305 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003306 case EventEntry::Type::CONFIGURATION_CHANGED:
3307 case EventEntry::Type::DEVICE_RESET: {
3308 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003309 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003310 break;
3311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
3313
3314 // Remember that we are waiting for this dispatch to complete.
3315 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003316 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 }
3318
3319 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003320 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003321 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003322}
3323
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003324/**
3325 * This function is purely for debugging. It helps us understand where the user interaction
3326 * was taking place. For example, if user is touching launcher, we will see a log that user
3327 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3328 * We will see both launcher and wallpaper in that list.
3329 * Once the interaction with a particular set of connections starts, no new logs will be printed
3330 * until the set of interacted connections changes.
3331 *
3332 * The following items are skipped, to reduce the logspam:
3333 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3334 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3335 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3336 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3337 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003338 */
3339void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3340 const std::vector<InputTarget>& targets) {
3341 // Skip ACTION_UP events, and all events other than keys and motions
3342 if (entry.type == EventEntry::Type::KEY) {
3343 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3344 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3345 return;
3346 }
3347 } else if (entry.type == EventEntry::Type::MOTION) {
3348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3349 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3350 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3351 return;
3352 }
3353 } else {
3354 return; // Not a key or a motion
3355 }
3356
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003357 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003358 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003359 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003360 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003361 continue; // Skip windows that receive ACTION_OUTSIDE
3362 }
3363
3364 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003365 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003366 if (connection == nullptr) {
3367 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003368 }
3369 newConnectionTokens.insert(std::move(token));
3370 newConnections.emplace_back(connection);
3371 }
3372 if (newConnectionTokens == mInteractionConnectionTokens) {
3373 return; // no change
3374 }
3375 mInteractionConnectionTokens = newConnectionTokens;
3376
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003377 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003378 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003379 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003380 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003381 std::string message = "Interaction with: " + targetList;
3382 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003383 message += "<none>";
3384 }
3385 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3386}
3387
chaviwfd6d3512019-03-25 13:23:49 -07003388void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003389 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003390 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003391 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3392 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003393 return;
3394 }
3395
Vishnu Nairc519ff72021-01-21 08:23:08 -08003396 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003397 if (focusedToken == token) {
3398 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003399 return;
3400 }
3401
Prabir Pradhancef936d2021-07-21 16:17:52 +00003402 auto command = [this, token]() REQUIRES(mLock) {
3403 scoped_unlock unlock(mLock);
3404 mPolicy->onPointerDownOutsideFocus(token);
3405 };
3406 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407}
3408
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003409status_t InputDispatcher::publishMotionEvent(Connection& connection,
3410 DispatchEntry& dispatchEntry) const {
3411 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3412 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3413
3414 PointerCoords scaledCoords[MAX_POINTERS];
3415 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3416
3417 // Set the X and Y offset and X and Y scale depending on the input source.
3418 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003419 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003420 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3421 if (globalScaleFactor != 1.0f) {
3422 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3423 scaledCoords[i] = motionEntry.pointerCoords[i];
3424 // Don't apply window scale here since we don't want scale to affect raw
3425 // coordinates. The scale will be sent back to the client and applied
3426 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003427 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003428 }
3429 usingCoords = scaledCoords;
3430 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003431 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003432 // We don't want the dispatch target to know the coordinates
3433 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3434 scaledCoords[i].clear();
3435 }
3436 usingCoords = scaledCoords;
3437 }
3438
3439 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3440
3441 // Publish the motion event.
3442 return connection.inputPublisher
3443 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3444 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3445 std::move(hmac), dispatchEntry.resolvedAction,
3446 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3447 motionEntry.edgeFlags, motionEntry.metaState,
3448 motionEntry.buttonState, motionEntry.classification,
3449 dispatchEntry.transform, motionEntry.xPrecision,
3450 motionEntry.yPrecision, motionEntry.xCursorPosition,
3451 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3452 motionEntry.downTime, motionEntry.eventTime,
3453 motionEntry.pointerCount, motionEntry.pointerProperties,
3454 usingCoords);
3455}
3456
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003458 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003459 if (ATRACE_ENABLED()) {
3460 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003462 ATRACE_NAME(message.c_str());
3463 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003464 if (DEBUG_DISPATCH_CYCLE) {
3465 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003468 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003469 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003471 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003472 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473
3474 // Publish the event.
3475 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003476 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3477 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003478 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003479 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3480 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003481 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3482 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3483 << connection->getInputChannelName();
3484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003486 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003487 status = connection->inputPublisher
3488 .publishKeyEvent(dispatchEntry->seq,
3489 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3490 keyEntry.source, keyEntry.displayId,
3491 std::move(hmac), dispatchEntry->resolvedAction,
3492 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3493 keyEntry.scanCode, keyEntry.metaState,
3494 keyEntry.repeatCount, keyEntry.downTime,
3495 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003496 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 }
3498
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003499 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003500 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3501 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3502 << connection->getInputChannelName();
3503 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003504 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003505 break;
3506 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003507
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003508 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003509 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003510 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003511 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003512 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003513 break;
3514 }
3515
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003516 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3517 const TouchModeEntry& touchModeEntry =
3518 static_cast<const TouchModeEntry&>(eventEntry);
3519 status = connection->inputPublisher
3520 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3521 touchModeEntry.inTouchMode);
3522
3523 break;
3524 }
3525
Prabir Pradhan99987712020-11-10 18:43:05 -08003526 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3527 const auto& captureEntry =
3528 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3529 status = connection->inputPublisher
3530 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003531 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003532 break;
3533 }
3534
arthurhungb89ccb02020-12-30 16:19:01 +08003535 case EventEntry::Type::DRAG: {
3536 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3537 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3538 dragEntry.id, dragEntry.x,
3539 dragEntry.y,
3540 dragEntry.isExiting);
3541 break;
3542 }
3543
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003544 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003545 case EventEntry::Type::DEVICE_RESET:
3546 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003547 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003548 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003549 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
3552
3553 // Check the result.
3554 if (status) {
3555 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003556 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003558 "This is unexpected because the wait queue is empty, so the pipe "
3559 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003560 "event to it, status=%s(%d)",
3561 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3562 status);
Harry Cutts33476232023-01-30 19:57:29 +00003563 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 } else {
3565 // Pipe is full and we are waiting for the app to finish process some events
3566 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003567 if (DEBUG_DISPATCH_CYCLE) {
3568 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3569 "waiting for the application to catch up",
3570 connection->getInputChannelName().c_str());
3571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 }
3573 } else {
3574 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003575 "status=%s(%d)",
3576 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3577 status);
Harry Cutts33476232023-01-30 19:57:29 +00003578 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580 return;
3581 }
3582
3583 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003584 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3585 connection->outboundQueue.end(),
3586 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003587 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003588 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003589 if (connection->responsive) {
3590 mAnrTracker.insert(dispatchEntry->timeoutTime,
3591 connection->inputChannel->getConnectionToken());
3592 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003593 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595}
3596
chaviw09c8d2d2020-08-24 15:48:26 -07003597std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3598 size_t size;
3599 switch (event.type) {
3600 case VerifiedInputEvent::Type::KEY: {
3601 size = sizeof(VerifiedKeyEvent);
3602 break;
3603 }
3604 case VerifiedInputEvent::Type::MOTION: {
3605 size = sizeof(VerifiedMotionEvent);
3606 break;
3607 }
3608 }
3609 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3610 return mHmacKeyManager.sign(start, size);
3611}
3612
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003613const std::array<uint8_t, 32> InputDispatcher::getSignature(
3614 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003615 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3616 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003617 // Only sign events up and down events as the purely move events
3618 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003619 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003620 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003621
3622 VerifiedMotionEvent verifiedEvent =
3623 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3624 verifiedEvent.actionMasked = actionMasked;
3625 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3626 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003627}
3628
3629const std::array<uint8_t, 32> InputDispatcher::getSignature(
3630 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3631 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3632 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3633 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003634 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003635}
3636
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003638 const std::shared_ptr<Connection>& connection,
3639 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003640 if (DEBUG_DISPATCH_CYCLE) {
3641 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3642 connection->getInputChannelName().c_str(), seq, toString(handled));
3643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003645 if (connection->status == Connection::Status::BROKEN ||
3646 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 return;
3648 }
3649
3650 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003651 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3652 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3653 };
3654 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655}
3656
3657void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003658 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003660 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003661 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3662 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664
3665 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003666 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003667 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003668 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003669 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670
3671 // The connection appears to be unrecoverably broken.
3672 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003673 if (connection->status == Connection::Status::NORMAL) {
3674 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
3676 if (notify) {
3677 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003678 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3679 connection->getInputChannelName().c_str());
3680
3681 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003682 scoped_unlock unlock(mLock);
3683 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3684 };
3685 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 }
3687 }
3688}
3689
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003690void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3691 while (!queue.empty()) {
3692 DispatchEntry* dispatchEntry = queue.front();
3693 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003694 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 }
3696}
3697
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003698void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003700 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702 delete dispatchEntry;
3703}
3704
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003705int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3706 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003707 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003708 if (connection == nullptr) {
3709 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3710 connectionToken.get(), events);
3711 return 0; // remove the callback
3712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003714 bool notify;
3715 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3716 if (!(events & ALOOPER_EVENT_INPUT)) {
3717 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3718 "events=0x%x",
3719 connection->getInputChannelName().c_str(), events);
3720 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 }
3722
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003723 nsecs_t currentTime = now();
3724 bool gotOne = false;
3725 status_t status = OK;
3726 for (;;) {
3727 Result<InputPublisher::ConsumerResponse> result =
3728 connection->inputPublisher.receiveConsumerResponse();
3729 if (!result.ok()) {
3730 status = result.error().code();
3731 break;
3732 }
3733
3734 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3735 const InputPublisher::Finished& finish =
3736 std::get<InputPublisher::Finished>(*result);
3737 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3738 finish.consumeTime);
3739 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003740 if (shouldReportMetricsForConnection(*connection)) {
3741 const InputPublisher::Timeline& timeline =
3742 std::get<InputPublisher::Timeline>(*result);
3743 mLatencyTracker
3744 .trackGraphicsLatency(timeline.inputEventId,
3745 connection->inputChannel->getConnectionToken(),
3746 std::move(timeline.graphicsTimeline));
3747 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003748 }
3749 gotOne = true;
3750 }
3751 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003752 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003753 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 return 1;
3755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
3757
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003758 notify = status != DEAD_OBJECT || !connection->monitor;
3759 if (notify) {
3760 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3761 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3762 status);
3763 }
3764 } else {
3765 // Monitor channels are never explicitly unregistered.
3766 // We do it automatically when the remote endpoint is closed so don't warn about them.
3767 const bool stillHaveWindowHandle =
3768 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3769 notify = !connection->monitor && stillHaveWindowHandle;
3770 if (notify) {
3771 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3772 connection->getInputChannelName().c_str(), events);
3773 }
3774 }
3775
3776 // Remove the channel.
3777 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3778 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779}
3780
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003781void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003783 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003784 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786}
3787
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003789 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003790 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003791 for (const Monitor& monitor : monitors) {
3792 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003793 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003794 }
3795}
3796
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003798 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003799 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003800 if (connection == nullptr) {
3801 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003803
3804 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805}
3806
3807void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003808 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003809 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 return;
3811 }
3812
3813 nsecs_t currentTime = now();
3814
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003815 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003816 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003818 if (cancelationEvents.empty()) {
3819 return;
3820 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003821 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3822 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003823 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003824 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003825 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003826 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003827
Arthur Hungb3307ee2021-10-14 10:57:37 +00003828 std::string reason = std::string("reason=").append(options.reason);
3829 android_log_event_list(LOGTAG_INPUT_CANCEL)
3830 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3831
Svet Ganov5d3bc372020-01-26 23:11:07 -08003832 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003833 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003834 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3835 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003836 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003837 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003838 target.globalScaleFactor = windowInfo->globalScaleFactor;
3839 }
3840 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003841 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003842
hongzuo liu95785e22022-09-06 02:51:35 +00003843 const bool wasEmpty = connection->outboundQueue.empty();
3844
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003845 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003846 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003847 switch (cancelationEventEntry->type) {
3848 case EventEntry::Type::KEY: {
3849 logOutboundKeyDetails("cancel - ",
3850 static_cast<const KeyEntry&>(*cancelationEventEntry));
3851 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003853 case EventEntry::Type::MOTION: {
3854 logOutboundMotionDetails("cancel - ",
3855 static_cast<const MotionEntry&>(*cancelationEventEntry));
3856 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003858 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003859 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003860 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3861 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003862 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003863 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003864 break;
3865 }
3866 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003867 case EventEntry::Type::DEVICE_RESET:
3868 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003869 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003870 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003871 break;
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003875 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003876 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003878
hongzuo liu95785e22022-09-06 02:51:35 +00003879 // If the outbound queue was previously empty, start the dispatch cycle going.
3880 if (wasEmpty && !connection->outboundQueue.empty()) {
3881 startDispatchCycleLocked(currentTime, connection);
3882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883}
3884
Svet Ganov5d3bc372020-01-26 23:11:07 -08003885void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003886 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003887 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003888 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003889 return;
3890 }
3891
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003892 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003893 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003894
3895 if (downEvents.empty()) {
3896 return;
3897 }
3898
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003899 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003900 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3901 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003902 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003903
3904 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003905 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003906 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3907 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003908 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003909 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003910 target.globalScaleFactor = windowInfo->globalScaleFactor;
3911 }
3912 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003913 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003914
hongzuo liu95785e22022-09-06 02:51:35 +00003915 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003916 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003917 switch (downEventEntry->type) {
3918 case EventEntry::Type::MOTION: {
3919 logOutboundMotionDetails("down - ",
3920 static_cast<const MotionEntry&>(*downEventEntry));
3921 break;
3922 }
3923
3924 case EventEntry::Type::KEY:
3925 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003926 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003927 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003928 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003929 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003930 case EventEntry::Type::SENSOR:
3931 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003932 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003933 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003934 break;
3935 }
3936 }
3937
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003938 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003939 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003940 }
3941
hongzuo liu95785e22022-09-06 02:51:35 +00003942 // If the outbound queue was previously empty, start the dispatch cycle going.
3943 if (wasEmpty && !connection->outboundQueue.empty()) {
3944 startDispatchCycleLocked(downTime, connection);
3945 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003946}
3947
Arthur Hungc539dbb2022-12-08 07:45:36 +00003948void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3949 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3950 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003951 std::shared_ptr<Connection> wallpaperConnection =
3952 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00003953 if (wallpaperConnection != nullptr) {
3954 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3955 }
3956 }
3957}
3958
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003959std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003960 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3961 nsecs_t splitDownTime) {
3962 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963
3964 uint32_t splitPointerIndexMap[MAX_POINTERS];
3965 PointerProperties splitPointerProperties[MAX_POINTERS];
3966 PointerCoords splitPointerCoords[MAX_POINTERS];
3967
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003968 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 uint32_t splitPointerCount = 0;
3970
3971 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003972 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003974 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003976 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3978 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3979 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003980 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 splitPointerCount += 1;
3982 }
3983 }
3984
3985 if (splitPointerCount != pointerIds.count()) {
3986 // This is bad. We are missing some of the pointers that we expected to deliver.
3987 // Most likely this indicates that we received an ACTION_MOVE events that has
3988 // different pointer ids than we expected based on the previous ACTION_DOWN
3989 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3990 // in this way.
3991 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003992 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003993 "a broken sequence of pointer ids from the input device: %s",
3994 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003995 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003998 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004000 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4001 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4003 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004004 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004006 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 if (pointerIds.count() == 1) {
4008 // The first/last pointer went down/up.
4009 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004011 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4012 ? AMOTION_EVENT_ACTION_CANCEL
4013 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 } else {
4015 // A secondary pointer went down/up.
4016 uint32_t splitPointerIndex = 0;
4017 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4018 splitPointerIndex += 1;
4019 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 action = maskedAction |
4021 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 }
4023 } else {
4024 // An unrelated pointer changed.
4025 action = AMOTION_EVENT_ACTION_MOVE;
4026 }
4027 }
4028
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004029 if (action == AMOTION_EVENT_ACTION_DOWN) {
4030 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
4031 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08004032 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4033 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004034 }
4035
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004036 int32_t newId = mIdGenerator.nextId();
4037 if (ATRACE_ENABLED()) {
4038 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4039 ") to MotionEvent(id=0x%" PRIx32 ").",
4040 originalMotionEntry.id, newId);
4041 ATRACE_NAME(message.c_str());
4042 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004043 std::unique_ptr<MotionEntry> splitMotionEntry =
4044 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4045 originalMotionEntry.deviceId, originalMotionEntry.source,
4046 originalMotionEntry.displayId,
4047 originalMotionEntry.policyFlags, action,
4048 originalMotionEntry.actionButton,
4049 originalMotionEntry.flags, originalMotionEntry.metaState,
4050 originalMotionEntry.buttonState,
4051 originalMotionEntry.classification,
4052 originalMotionEntry.edgeFlags,
4053 originalMotionEntry.xPrecision,
4054 originalMotionEntry.yPrecision,
4055 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004056 originalMotionEntry.yCursorPosition, splitDownTime,
4057 splitPointerCount, splitPointerProperties,
4058 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004060 if (originalMotionEntry.injectionState) {
4061 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 splitMotionEntry->injectionState->refCount += 1;
4063 }
4064
4065 return splitMotionEntry;
4066}
4067
Prabir Pradhan678438e2023-04-13 19:32:51 +00004068void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004069 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004070 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Antonio Kantekf16f2832021-09-28 04:39:20 +00004073 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004075 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004077 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004078 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 } // release lock
4081
4082 if (needWake) {
4083 mLooper->wake();
4084 }
4085}
4086
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004087/**
4088 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004089 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4090 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4091 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4092 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4093 * potentially handle the back key presses.
4094 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4095 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004096 */
4097void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004099 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4100 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004101 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004102 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004103 }
4104 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004105 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004106 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004107 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004108 keyCode = newKeyCode;
4109 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4110 }
4111 } else if (action == AKEY_EVENT_ACTION_UP) {
4112 // In order to maintain a consistent stream of up and down events, check to see if the key
4113 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4114 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004115 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004116 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004117 auto replacementIt = mReplacedKeys.find(replacement);
4118 if (replacementIt != mReplacedKeys.end()) {
4119 keyCode = replacementIt->second;
4120 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004121 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4122 }
4123 }
4124}
4125
Prabir Pradhan678438e2023-04-13 19:32:51 +00004126void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004127 ALOGD_IF(debugInboundEventDetails(),
4128 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4129 ", deviceId=%d, source=%s, displayId=%" PRId32
4130 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4131 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004132 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4133 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4134 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004135 Result<void> keyCheck = validateKeyEvent(args.action);
4136 if (!keyCheck.ok()) {
4137 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 return;
4139 }
4140
Prabir Pradhan678438e2023-04-13 19:32:51 +00004141 uint32_t policyFlags = args.policyFlags;
4142 int32_t flags = args.flags;
4143 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004144 // InputDispatcher tracks and generates key repeats on behalf of
4145 // whatever notifies it, so repeatCount should always be set to 0
4146 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4148 policyFlags |= POLICY_FLAG_VIRTUAL;
4149 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 if (policyFlags & POLICY_FLAG_FUNCTION) {
4152 metaState |= AMETA_FUNCTION_ON;
4153 }
4154
4155 policyFlags |= POLICY_FLAG_TRUSTED;
4156
Prabir Pradhan678438e2023-04-13 19:32:51 +00004157 int32_t keyCode = args.keyCode;
4158 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004159
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004161 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4162 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4163 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
Michael Wright2b3c3302018-03-02 17:19:13 +00004165 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004167 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4168 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004169 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171
Antonio Kantekf16f2832021-09-28 04:39:20 +00004172 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 { // acquire lock
4174 mLock.lock();
4175
4176 if (shouldSendKeyToInputFilterLocked(args)) {
4177 mLock.unlock();
4178
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004179 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4181 return; // event was consumed by the filter
4182 }
4183
4184 mLock.lock();
4185 }
4186
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004187 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004188 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4189 args.displayId, policyFlags, args.action, flags, keyCode,
4190 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004192 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 mLock.unlock();
4194 } // release lock
4195
4196 if (needWake) {
4197 mLooper->wake();
4198 }
4199}
4200
Prabir Pradhan678438e2023-04-13 19:32:51 +00004201bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 return mInputFilterEnabled;
4203}
4204
Prabir Pradhan678438e2023-04-13 19:32:51 +00004205void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004206 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004207 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004208 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004209 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004210 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4211 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004212 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4213 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4214 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4215 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4216 args.downTime);
4217 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004218 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4219 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004220 i, args.pointerProperties[i].id,
4221 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4222 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4223 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4224 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4225 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4226 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4227 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4228 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4229 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4230 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004233
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004234 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4235 args.pointerCount, args.pointerProperties);
4236 if (!motionCheck.ok()) {
4237 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004238 return;
4239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Prabir Pradhan678438e2023-04-13 19:32:51 +00004241 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004243
4244 android::base::Timer t;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004245 mPolicy->interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004246 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4247 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250
Antonio Kantekf16f2832021-09-28 04:39:20 +00004251 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 { // acquire lock
4253 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004254 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4255 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4256 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004257 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004258 if (touchStateIt != mTouchStatesByDisplay.end()) {
4259 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004260 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004261 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4262 }
4263 }
4264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
4266 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004267 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004268 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004269 displayTransform = it->second.transform;
4270 }
4271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 mLock.unlock();
4273
4274 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004275 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4276 args.action, args.actionButton, args.flags, args.edgeFlags,
4277 args.metaState, args.buttonState, args.classification,
4278 displayTransform, args.xPrecision, args.yPrecision,
4279 args.xCursorPosition, args.yCursorPosition, displayTransform,
4280 args.downTime, args.eventTime, args.pointerCount,
4281 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282
4283 policyFlags |= POLICY_FLAG_FILTERED;
4284 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4285 return; // event was consumed by the filter
4286 }
4287
4288 mLock.lock();
4289 }
4290
4291 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004292 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004293 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4294 args.displayId, policyFlags, args.action,
4295 args.actionButton, args.flags, args.metaState,
4296 args.buttonState, args.classification, args.edgeFlags,
4297 args.xPrecision, args.yPrecision,
4298 args.xCursorPosition, args.yCursorPosition,
4299 args.downTime, args.pointerCount,
4300 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301
Prabir Pradhan678438e2023-04-13 19:32:51 +00004302 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4303 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004304 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004305 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4306 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004307 }
4308
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004309 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 mLock.unlock();
4311 } // release lock
4312
4313 if (needWake) {
4314 mLooper->wake();
4315 }
4316}
4317
Prabir Pradhan678438e2023-04-13 19:32:51 +00004318void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004319 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004320 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4321 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004322 args.id, args.eventTime, args.deviceId, args.source,
4323 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004324 }
Chris Yef59a2f42020-10-16 12:55:26 -07004325
Antonio Kantekf16f2832021-09-28 04:39:20 +00004326 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004327 { // acquire lock
4328 mLock.lock();
4329
4330 // Just enqueue a new sensor event.
4331 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004332 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4333 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4334 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004335
4336 needWake = enqueueInboundEventLocked(std::move(newEntry));
4337 mLock.unlock();
4338 } // release lock
4339
4340 if (needWake) {
4341 mLooper->wake();
4342 }
4343}
4344
Prabir Pradhan678438e2023-04-13 19:32:51 +00004345void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004346 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004347 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4348 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004349 }
Prabir Pradhan678438e2023-04-13 19:32:51 +00004350 mPolicy->notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004351}
4352
Prabir Pradhan678438e2023-04-13 19:32:51 +00004353bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004354 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355}
4356
Prabir Pradhan678438e2023-04-13 19:32:51 +00004357void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004358 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004359 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4360 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004361 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363
Prabir Pradhan678438e2023-04-13 19:32:51 +00004364 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004366 mPolicy->notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367}
4368
Prabir Pradhan678438e2023-04-13 19:32:51 +00004369void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004370 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004371 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4372 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
Antonio Kantekf16f2832021-09-28 04:39:20 +00004375 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004377 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004379 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004380 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004381 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 } // release lock
4383
4384 if (needWake) {
4385 mLooper->wake();
4386 }
4387}
4388
Prabir Pradhan678438e2023-04-13 19:32:51 +00004389void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004390 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004391 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4392 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004393 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004394
Antonio Kantekf16f2832021-09-28 04:39:20 +00004395 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004396 { // acquire lock
4397 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004398 auto entry =
4399 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004400 needWake = enqueueInboundEventLocked(std::move(entry));
4401 } // release lock
4402
4403 if (needWake) {
4404 mLooper->wake();
4405 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004406}
4407
Prabir Pradhan5735a322022-04-11 17:23:34 +00004408InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4409 std::optional<int32_t> targetUid,
4410 InputEventInjectionSync syncMode,
4411 std::chrono::milliseconds timeout,
4412 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004413 Result<void> eventValidation = validateInputEvent(*event);
4414 if (!eventValidation.ok()) {
4415 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4416 return InputEventInjectionResult::FAILED;
4417 }
4418
Prabir Pradhan65613802023-02-22 23:36:58 +00004419 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004420 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4421 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4422 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4423 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004424 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004425 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426
Prabir Pradhan5735a322022-04-11 17:23:34 +00004427 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004429 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004430 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4431 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4432 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4433 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4434 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004435 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004436 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004437 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004438 }
4439
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004440 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004442 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004443 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004444 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004445 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004446 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4447 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4448 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004449 int32_t keyCode = incomingKey.getKeyCode();
4450 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004451 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004453 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004454 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004455 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4456 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4457 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4460 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004461 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004462
4463 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4464 android::base::Timer t;
4465 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4466 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4467 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4468 std::to_string(t.duration().count()).c_str());
4469 }
4470 }
4471
4472 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004473 std::unique_ptr<KeyEntry> injectedEntry =
4474 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004475 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004476 incomingKey.getDisplayId(), policyFlags, action,
4477 flags, keyCode, incomingKey.getScanCode(), metaState,
4478 incomingKey.getRepeatCount(),
4479 incomingKey.getDownTime());
4480 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004481 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004484 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004485 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004486 const bool isPointerEvent =
4487 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4488 // If a pointer event has no displayId specified, inject it to the default display.
4489 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4490 ? ADISPLAY_ID_DEFAULT
4491 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004492 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004493
4494 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004495 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 android::base::Timer t;
4497 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4498 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4499 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4500 std::to_string(t.duration().count()).c_str());
4501 }
4502 }
4503
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004504 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4505 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4506 }
4507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004508 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004509 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4510 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004511 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004512 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4513 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004514 displayId, policyFlags, motionEvent.getAction(),
4515 motionEvent.getActionButton(), flags,
4516 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004517 motionEvent.getButtonState(),
4518 motionEvent.getClassification(),
4519 motionEvent.getEdgeFlags(),
4520 motionEvent.getXPrecision(),
4521 motionEvent.getYPrecision(),
4522 motionEvent.getRawXCursorPosition(),
4523 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004524 motionEvent.getDownTime(),
4525 motionEvent.getPointerCount(),
4526 motionEvent.getPointerProperties(),
4527 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004528 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004529 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004530 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004532 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004533 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004534 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4535 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004536 displayId, policyFlags,
4537 motionEvent.getAction(),
4538 motionEvent.getActionButton(), flags,
4539 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004540 motionEvent.getButtonState(),
4541 motionEvent.getClassification(),
4542 motionEvent.getEdgeFlags(),
4543 motionEvent.getXPrecision(),
4544 motionEvent.getYPrecision(),
4545 motionEvent.getRawXCursorPosition(),
4546 motionEvent.getRawYCursorPosition(),
4547 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004548 motionEvent.getPointerCount(),
4549 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004550 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004551 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4552 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004553 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004554 }
4555 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004558 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004559 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004560 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 }
4562
Prabir Pradhan5735a322022-04-11 17:23:34 +00004563 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004564 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 injectionState->injectionIsAsync = true;
4566 }
4567
4568 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004569 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
4571 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004572 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004573 if (DEBUG_INJECTION) {
4574 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4575 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004576 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004577 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579
4580 mLock.unlock();
4581
4582 if (needWake) {
4583 mLooper->wake();
4584 }
4585
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004588 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004590 if (syncMode == InputEventInjectionSync::NONE) {
4591 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 } else {
4593 for (;;) {
4594 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004595 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 break;
4597 }
4598
4599 nsecs_t remainingTimeout = endTime - now();
4600 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004601 if (DEBUG_INJECTION) {
4602 ALOGD("injectInputEvent - Timed out waiting for injection result "
4603 "to become available.");
4604 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004605 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 break;
4607 }
4608
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004609 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 }
4611
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004612 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4613 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004615 if (DEBUG_INJECTION) {
4616 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4617 injectionState->pendingForegroundDispatches);
4618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 nsecs_t remainingTimeout = endTime - now();
4620 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004621 if (DEBUG_INJECTION) {
4622 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4623 "dispatches to finish.");
4624 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004625 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 break;
4627 }
4628
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004629 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 }
4631 }
4632 }
4633
4634 injectionState->release();
4635 } // release lock
4636
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004637 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004638 LOG(DEBUG) << "injectInputEvent - Finished with result "
4639 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641
4642 return injectionResult;
4643}
4644
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004645std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004646 std::array<uint8_t, 32> calculatedHmac;
4647 std::unique_ptr<VerifiedInputEvent> result;
4648 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004649 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004650 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4651 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4652 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004653 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004654 break;
4655 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004656 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004657 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4658 VerifiedMotionEvent verifiedMotionEvent =
4659 verifiedMotionEventFromMotionEvent(motionEvent);
4660 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004661 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004662 break;
4663 }
4664 default: {
4665 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4666 return nullptr;
4667 }
4668 }
4669 if (calculatedHmac == INVALID_HMAC) {
4670 return nullptr;
4671 }
tyiu1573a672023-02-21 22:38:32 +00004672 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004673 return nullptr;
4674 }
4675 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004676}
4677
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004678void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004679 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004680 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004682 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004683 LOG(DEBUG) << "Setting input event injection result to "
4684 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004687 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 // Log the outcome since the injector did not wait for the injection result.
4689 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004690 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004691 ALOGV("Asynchronous input event injection succeeded.");
4692 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004693 case InputEventInjectionResult::TARGET_MISMATCH:
4694 ALOGV("Asynchronous input event injection target mismatch.");
4695 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004696 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004697 ALOGW("Asynchronous input event injection failed.");
4698 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004699 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700 ALOGW("Asynchronous input event injection timed out.");
4701 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 case InputEventInjectionResult::PENDING:
4703 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4704 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 }
4706 }
4707
4708 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004709 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 }
4711}
4712
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004713void InputDispatcher::transformMotionEntryForInjectionLocked(
4714 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004715 // Input injection works in the logical display coordinate space, but the input pipeline works
4716 // display space, so we need to transform the injected events accordingly.
4717 const auto it = mDisplayInfos.find(entry.displayId);
4718 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004719 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004720
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004721 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4722 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4723 const vec2 cursor =
4724 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4725 {entry.xCursorPosition, entry.yCursorPosition});
4726 entry.xCursorPosition = cursor.x;
4727 entry.yCursorPosition = cursor.y;
4728 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004729 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004730 entry.pointerCoords[i] =
4731 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4732 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004733 }
4734}
4735
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004736void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4737 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 if (injectionState) {
4739 injectionState->pendingForegroundDispatches += 1;
4740 }
4741}
4742
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004743void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4744 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 if (injectionState) {
4746 injectionState->pendingForegroundDispatches -= 1;
4747
4748 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004749 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 }
4751 }
4752}
4753
chaviw98318de2021-05-19 16:45:23 -05004754const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004755 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004756 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004757 auto it = mWindowHandlesByDisplay.find(displayId);
4758 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004759}
4760
chaviw98318de2021-05-19 16:45:23 -05004761sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004762 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004763 if (windowHandleToken == nullptr) {
4764 return nullptr;
4765 }
4766
Arthur Hungb92218b2018-08-14 12:00:21 +08004767 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004768 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4769 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004770 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004771 return windowHandle;
4772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 }
4774 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004775 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776}
4777
chaviw98318de2021-05-19 16:45:23 -05004778sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4779 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004780 if (windowHandleToken == nullptr) {
4781 return nullptr;
4782 }
4783
chaviw98318de2021-05-19 16:45:23 -05004784 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004785 if (windowHandle->getToken() == windowHandleToken) {
4786 return windowHandle;
4787 }
4788 }
4789 return nullptr;
4790}
4791
chaviw98318de2021-05-19 16:45:23 -05004792sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4793 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004794 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004795 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4796 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004797 if (handle->getId() == windowHandle->getId() &&
4798 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004799 if (windowHandle->getInfo()->displayId != it.first) {
4800 ALOGE("Found window %s in display %" PRId32
4801 ", but it should belong to display %" PRId32,
4802 windowHandle->getName().c_str(), it.first,
4803 windowHandle->getInfo()->displayId);
4804 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004805 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 }
4808 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004809 return nullptr;
4810}
4811
chaviw98318de2021-05-19 16:45:23 -05004812sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004813 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4814 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815}
4816
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004817ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4818 auto displayInfoIt = mDisplayInfos.find(displayId);
4819 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4820 : kIdentityTransform;
4821}
4822
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004823bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4824 const MotionEntry& motionEntry) const {
4825 const WindowInfo& info = *window->getInfo();
4826
4827 // Skip spy window targets that are not valid for targeted injection.
4828 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004829 return false;
4830 }
4831
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004832 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4833 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4834 return false;
4835 }
4836
4837 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4838 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4839 window->getName().c_str());
4840 return false;
4841 }
4842
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004843 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004844 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004845 ALOGW("Not sending touch to %s because there's no corresponding connection",
4846 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004847 return false;
4848 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004849
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004850 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004851 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004852 return false;
4853 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004854
4855 // Drop events that can't be trusted due to occlusion
4856 const auto [x, y] = resolveTouchedPosition(motionEntry);
4857 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4858 if (!isTouchTrustedLocked(occlusionInfo)) {
4859 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004860 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004861 for (const auto& log : occlusionInfo.debugInfo) {
4862 ALOGD("%s", log.c_str());
4863 }
4864 }
4865 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4866 occlusionInfo.obscuringUid);
4867 return false;
4868 }
4869
4870 // Drop touch events if requested by input feature
4871 if (shouldDropInput(motionEntry, window)) {
4872 return false;
4873 }
4874
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004875 return true;
4876}
4877
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004878std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4879 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004880 auto connectionIt = mConnectionsByToken.find(token);
4881 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004882 return nullptr;
4883 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004884 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004885}
4886
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004887void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004888 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4889 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004890 // Remove all handles on a display if there are no windows left.
4891 mWindowHandlesByDisplay.erase(displayId);
4892 return;
4893 }
4894
4895 // Since we compare the pointer of input window handles across window updates, we need
4896 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004897 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4898 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4899 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004900 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004901 }
4902
chaviw98318de2021-05-19 16:45:23 -05004903 std::vector<sp<WindowInfoHandle>> newHandles;
4904 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004905 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004906 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004907 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004908 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004909 const bool canReceiveInput =
4910 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4911 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004912 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004913 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004914 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004915 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004916 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004917 }
4918
4919 if (info->displayId != displayId) {
4920 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4921 handle->getName().c_str(), displayId, info->displayId);
4922 continue;
4923 }
4924
Robert Carredd13602020-04-13 17:24:34 -07004925 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4926 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004927 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004928 oldHandle->updateFrom(handle);
4929 newHandles.push_back(oldHandle);
4930 } else {
4931 newHandles.push_back(handle);
4932 }
4933 }
4934
4935 // Insert or replace
4936 mWindowHandlesByDisplay[displayId] = newHandles;
4937}
4938
Arthur Hung72d8dc32020-03-28 00:48:39 +00004939void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004940 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004941 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004942 { // acquire lock
4943 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004944 for (const auto& [displayId, handles] : handlesPerDisplay) {
4945 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004946 }
4947 }
4948 // Wake up poll loop since it may need to make new input dispatching choices.
4949 mLooper->wake();
4950}
4951
Arthur Hungb92218b2018-08-14 12:00:21 +08004952/**
4953 * Called from InputManagerService, update window handle list by displayId that can receive input.
4954 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4955 * If set an empty list, remove all handles from the specific display.
4956 * For focused handle, check if need to change and send a cancel event to previous one.
4957 * For removed handle, check if need to send a cancel event if already in touch.
4958 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004959void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004960 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004961 if (DEBUG_FOCUS) {
4962 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004963 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004964 windowList += iwh->getName() + " ";
4965 }
4966 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968
Prabir Pradhand65552b2021-10-07 11:23:50 -07004969 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004970 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004971 const WindowInfo& info = *window->getInfo();
4972
4973 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004974 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004975 if (noInputWindow && window->getToken() != nullptr) {
4976 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4977 window->getName().c_str());
4978 window->releaseChannel();
4979 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004980
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004981 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004982 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4983 !info.inputConfig.test(
4984 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004985 "%s has feature SPY, but is not a trusted overlay.",
4986 window->getName().c_str());
4987
Prabir Pradhand65552b2021-10-07 11:23:50 -07004988 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004989 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4990 !info.inputConfig.test(
4991 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004992 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4993 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004994 }
4995
Arthur Hung72d8dc32020-03-28 00:48:39 +00004996 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004997 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004999 // Save the old windows' orientation by ID before it gets updated.
5000 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005001 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005002 oldWindowOrientations.emplace(handle->getId(),
5003 handle->getInfo()->transform.getOrientation());
5004 }
5005
chaviw98318de2021-05-19 16:45:23 -05005006 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005007
chaviw98318de2021-05-19 16:45:23 -05005008 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005009
Vishnu Nairc519ff72021-01-21 08:23:08 -08005010 std::optional<FocusResolver::FocusChanges> changes =
5011 mFocusResolver.setInputWindows(displayId, windowHandles);
5012 if (changes) {
5013 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005016 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5017 mTouchStatesByDisplay.find(displayId);
5018 if (stateIt != mTouchStatesByDisplay.end()) {
5019 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005020 for (size_t i = 0; i < state.windows.size();) {
5021 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005022 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005023 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005024 ALOGD("Touched window was removed: %s in display %" PRId32,
5025 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005026 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005027 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005028 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5029 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005030 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005031 "touched window was removed");
5032 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005033 // Since we are about to drop the touch, cancel the events for the wallpaper as
5034 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005035 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005036 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5037 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005038 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005039 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005042 state.windows.erase(state.windows.begin() + i);
5043 } else {
5044 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 }
5046 }
arthurhungb89ccb02020-12-30 16:19:01 +08005047
arthurhung6d4bed92021-03-17 11:59:33 +08005048 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005049 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005050 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005051 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005052 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005053 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5054 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005055 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005056 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005057 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005058
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005059 // Determine if the orientation of any of the input windows have changed, and cancel all
5060 // pointer events if necessary.
5061 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5062 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5063 if (newWindowHandle != nullptr &&
5064 newWindowHandle->getInfo()->transform.getOrientation() !=
5065 oldWindowOrientations[oldWindowHandle->getId()]) {
5066 std::shared_ptr<InputChannel> inputChannel =
5067 getInputChannelLocked(newWindowHandle->getToken());
5068 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005069 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005070 "touched window's orientation changed");
5071 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005072 }
5073 }
5074 }
5075
Arthur Hung72d8dc32020-03-28 00:48:39 +00005076 // Release information for windows that are no longer present.
5077 // This ensures that unused input channels are released promptly.
5078 // Otherwise, they might stick around until the window handle is destroyed
5079 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005080 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005081 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005082 if (DEBUG_FOCUS) {
5083 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005084 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005085 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005086 }
chaviw291d88a2019-02-14 10:33:58 -08005087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088}
5089
5090void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005091 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005092 if (DEBUG_FOCUS) {
5093 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5094 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5095 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005096 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005097 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005098 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 } // release lock
5100
5101 // Wake up poll loop since it may need to make new input dispatching choices.
5102 mLooper->wake();
5103}
5104
Vishnu Nair599f1412021-06-21 10:39:58 -07005105void InputDispatcher::setFocusedApplicationLocked(
5106 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5107 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5108 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5109
5110 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5111 return; // This application is already focused. No need to wake up or change anything.
5112 }
5113
5114 // Set the new application handle.
5115 if (inputApplicationHandle != nullptr) {
5116 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5117 } else {
5118 mFocusedApplicationHandlesByDisplay.erase(displayId);
5119 }
5120
5121 // No matter what the old focused application was, stop waiting on it because it is
5122 // no longer focused.
5123 resetNoFocusedWindowTimeoutLocked();
5124}
5125
Tiger Huang721e26f2018-07-24 22:26:19 +08005126/**
5127 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5128 * the display not specified.
5129 *
5130 * We track any unreleased events for each window. If a window loses the ability to receive the
5131 * released event, we will send a cancel event to it. So when the focused display is changed, we
5132 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5133 * display. The display-specified events won't be affected.
5134 */
5135void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005136 if (DEBUG_FOCUS) {
5137 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5138 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005139 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005140 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005141
5142 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005143 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005144 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005145 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005146 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005147 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005148 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005149 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005150 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005151 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005152 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005153 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5154 }
5155 }
5156 mFocusedDisplayId = displayId;
5157
Chris Ye3c2d6f52020-08-09 10:39:48 -07005158 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005159 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005160 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005161
Vishnu Nairad321cd2020-08-20 16:40:21 -07005162 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005163 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005164 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005165 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005166 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005167 }
5168 }
5169 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005170 } // release lock
5171
5172 // Wake up poll loop since it may need to make new input dispatching choices.
5173 mLooper->wake();
5174}
5175
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005177 if (DEBUG_FOCUS) {
5178 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180
5181 bool changed;
5182 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005183 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184
5185 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5186 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005187 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 }
5189
5190 if (mDispatchEnabled && !enabled) {
5191 resetAndDropEverythingLocked("dispatcher is being disabled");
5192 }
5193
5194 mDispatchEnabled = enabled;
5195 mDispatchFrozen = frozen;
5196 changed = true;
5197 } else {
5198 changed = false;
5199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200 } // release lock
5201
5202 if (changed) {
5203 // Wake up poll loop since it may need to make new input dispatching choices.
5204 mLooper->wake();
5205 }
5206}
5207
5208void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005209 if (DEBUG_FOCUS) {
5210 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212
5213 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005214 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215
5216 if (mInputFilterEnabled == enabled) {
5217 return;
5218 }
5219
5220 mInputFilterEnabled = enabled;
5221 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5222 } // release lock
5223
5224 // Wake up poll loop since there might be work to do to drop everything.
5225 mLooper->wake();
5226}
5227
Antonio Kanteka042c022022-07-06 16:51:07 -07005228bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5229 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005230 bool needWake = false;
5231 {
5232 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005233 ALOGD_IF(DEBUG_TOUCH_MODE,
5234 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5235 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5236 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5237 mTouchModePerDisplay.count(displayId) == 0
5238 ? "not set"
5239 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5240
Antonio Kantek15beb512022-06-13 22:35:41 +00005241 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5242 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005243 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005244 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005245 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005246 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5247 !recentWindowsAreOwnedByLocked(pid, uid)) {
5248 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5249 "window nor none of the previously interacted window",
5250 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005251 return false;
5252 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005253 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005254 mTouchModePerDisplay[displayId] = inTouchMode;
5255 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5256 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005257 needWake = enqueueInboundEventLocked(std::move(entry));
5258 } // release lock
5259
5260 if (needWake) {
5261 mLooper->wake();
5262 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005263 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005264}
5265
Antonio Kantek48710e42022-03-24 14:19:30 -07005266bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5267 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5268 if (focusedToken == nullptr) {
5269 return false;
5270 }
5271 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5272 return isWindowOwnedBy(windowHandle, pid, uid);
5273}
5274
5275bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5276 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5277 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5278 const sp<WindowInfoHandle> windowHandle =
5279 getWindowHandleLocked(connectionToken);
5280 return isWindowOwnedBy(windowHandle, pid, uid);
5281 }) != mInteractionConnectionTokens.end();
5282}
5283
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005284void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5285 if (opacity < 0 || opacity > 1) {
5286 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5287 return;
5288 }
5289
5290 std::scoped_lock lock(mLock);
5291 mMaximumObscuringOpacityForTouch = opacity;
5292}
5293
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005294std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5295InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005296 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5297 for (TouchedWindow& w : state.windows) {
5298 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005299 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005300 }
5301 }
5302 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005303 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005304}
5305
arthurhungb89ccb02020-12-30 16:19:01 +08005306bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5307 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005308 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005309 if (DEBUG_FOCUS) {
5310 ALOGD("Trivial transfer to same window.");
5311 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005312 return true;
5313 }
5314
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005316 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317
Arthur Hungabbb9d82021-09-01 14:52:30 +00005318 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005319 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005320 if (state == nullptr || touchedWindow == nullptr) {
5321 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 return false;
5323 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005324
Arthur Hungabbb9d82021-09-01 14:52:30 +00005325 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5326 if (toWindowHandle == nullptr) {
5327 ALOGW("Cannot transfer focus because to window not found.");
5328 return false;
5329 }
5330
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005331 if (DEBUG_FOCUS) {
5332 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005333 touchedWindow->windowHandle->getName().c_str(),
5334 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336
Arthur Hungabbb9d82021-09-01 14:52:30 +00005337 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005338 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005339 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005340 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005341 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342
Arthur Hungabbb9d82021-09-01 14:52:30 +00005343 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005344 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005345 ftl::Flags<InputTarget::Flags> newTargetFlags =
5346 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005347 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005348 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005349 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005350 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
Arthur Hungabbb9d82021-09-01 14:52:30 +00005352 // Store the dragging window.
5353 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005354 if (pointerIds.count() != 1) {
5355 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5356 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005357 return false;
5358 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005359 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005360 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005361 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 }
5363
Arthur Hungabbb9d82021-09-01 14:52:30 +00005364 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005365 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5366 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005367 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005368 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005369 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005370 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005371 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005373 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5374 newTargetFlags);
5375
5376 // Check if the wallpaper window should deliver the corresponding event.
5377 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5378 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 } // release lock
5381
5382 // Wake up poll loop since it may need to make new input dispatching choices.
5383 mLooper->wake();
5384 return true;
5385}
5386
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005387/**
5388 * Get the touched foreground window on the given display.
5389 * Return null if there are no windows touched on that display, or if more than one foreground
5390 * window is being touched.
5391 */
5392sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5393 auto stateIt = mTouchStatesByDisplay.find(displayId);
5394 if (stateIt == mTouchStatesByDisplay.end()) {
5395 ALOGI("No touch state on display %" PRId32, displayId);
5396 return nullptr;
5397 }
5398
5399 const TouchState& state = stateIt->second;
5400 sp<WindowInfoHandle> touchedForegroundWindow;
5401 // If multiple foreground windows are touched, return nullptr
5402 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005403 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005404 if (touchedForegroundWindow != nullptr) {
5405 ALOGI("Two or more foreground windows: %s and %s",
5406 touchedForegroundWindow->getName().c_str(),
5407 window.windowHandle->getName().c_str());
5408 return nullptr;
5409 }
5410 touchedForegroundWindow = window.windowHandle;
5411 }
5412 }
5413 return touchedForegroundWindow;
5414}
5415
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005416// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005417bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005418 sp<IBinder> fromToken;
5419 { // acquire lock
5420 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005421 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005422 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005423 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5424 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005425 return false;
5426 }
5427
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005428 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5429 if (from == nullptr) {
5430 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5431 return false;
5432 }
5433
5434 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005435 } // release lock
5436
5437 return transferTouchFocus(fromToken, destChannelToken);
5438}
5439
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005441 if (DEBUG_FOCUS) {
5442 ALOGD("Resetting and dropping all events (%s).", reason);
5443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444
Michael Wrightfb04fd52022-11-24 22:31:11 +00005445 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 synthesizeCancelationEventsForAllConnectionsLocked(options);
5447
5448 resetKeyRepeatLocked();
5449 releasePendingEventLocked();
5450 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005451 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005453 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005454 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005455 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456}
5457
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005458void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005459 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 dumpDispatchStateLocked(dump);
5461
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005462 std::istringstream stream(dump);
5463 std::string line;
5464
5465 while (std::getline(stream, line, '\n')) {
5466 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 }
5468}
5469
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005470std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005471 std::string dump;
5472
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005473 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5474 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005475
5476 std::string windowName = "None";
5477 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005478 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005479 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5480 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5481 : "token has capture without window";
5482 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005483 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005484
5485 return dump;
5486}
5487
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005488void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005489 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5490 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5491 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005492 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493
Tiger Huang721e26f2018-07-24 22:26:19 +08005494 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5495 dump += StringPrintf(INDENT "FocusedApplications:\n");
5496 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5497 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005498 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005499 const std::chrono::duration timeout =
5500 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005501 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005502 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005503 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005506 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005508
Vishnu Nairc519ff72021-01-21 08:23:08 -08005509 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005510 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005512 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005513 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005514 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005515 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5516 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 }
5518 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005519 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 }
5521
arthurhung6d4bed92021-03-17 11:59:33 +08005522 if (mDragState) {
5523 dump += StringPrintf(INDENT "DragState:\n");
5524 mDragState->dump(dump, INDENT2);
5525 }
5526
Arthur Hungb92218b2018-08-14 12:00:21 +08005527 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005528 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5529 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5530 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5531 const auto& displayInfo = it->second;
5532 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5533 displayInfo.logicalHeight);
5534 displayInfo.transform.dump(dump, "transform", INDENT4);
5535 } else {
5536 dump += INDENT2 "No DisplayInfo found!\n";
5537 }
5538
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005539 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005540 dump += INDENT2 "Windows:\n";
5541 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005542 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5543 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005545 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005546 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005547 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005548 "applicationInfo.name=%s, "
5549 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005550 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005551 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005552 windowInfo->displayId,
5553 windowInfo->inputConfig.string().c_str(),
5554 windowInfo->alpha, windowInfo->frameLeft,
5555 windowInfo->frameTop, windowInfo->frameRight,
5556 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005557 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005558 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005559 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005560 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005561 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005562 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005563 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005564 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005565 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005566 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005567 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005568 }
5569 } else {
5570 dump += INDENT2 "Windows: <none>\n";
5571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 }
5573 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005574 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 }
5576
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005577 if (!mGlobalMonitorsByDisplay.empty()) {
5578 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5579 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005580 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005583 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 }
5585
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005586 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587
5588 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005589 if (!mRecentQueue.empty()) {
5590 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005591 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005592 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005593 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005594 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 }
5596 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005597 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 }
5599
5600 // Dump event currently being dispatched.
5601 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005602 dump += INDENT "PendingEvent:\n";
5603 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005604 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005605 dump += StringPrintf(", age=%" PRId64 "ms\n",
5606 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005608 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 }
5610
5611 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005612 if (!mInboundQueue.empty()) {
5613 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005614 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005615 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005616 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005617 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 }
5619 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005620 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 }
5622
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005623 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005624 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005625 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005626 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005627 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005628 }
5629 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005630 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005631 }
5632
Prabir Pradhancef936d2021-07-21 16:17:52 +00005633 if (!mCommandQueue.empty()) {
5634 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5635 } else {
5636 dump += INDENT "CommandQueue: <empty>\n";
5637 }
5638
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005639 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005640 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005641 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005642 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005643 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005644 connection->inputChannel->getFd().get(),
5645 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005646 connection->getWindowName().c_str(),
5647 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005648 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005650 if (!connection->outboundQueue.empty()) {
5651 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5652 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005653 dump += dumpQueue(connection->outboundQueue, currentTime);
5654
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005656 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 }
5658
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005659 if (!connection->waitQueue.empty()) {
5660 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5661 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005662 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005664 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 }
5666 }
5667 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005668 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 }
5670
5671 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005672 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5673 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005675 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 }
5677
Antonio Kantek15beb512022-06-13 22:35:41 +00005678 if (!mTouchModePerDisplay.empty()) {
5679 dump += INDENT "TouchModePerDisplay:\n";
5680 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5681 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5682 std::to_string(touchMode).c_str());
5683 }
5684 } else {
5685 dump += INDENT "TouchModePerDisplay: <none>\n";
5686 }
5687
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005688 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005689 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5690 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5691 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005692 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005693 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694}
5695
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005696void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005697 const size_t numMonitors = monitors.size();
5698 for (size_t i = 0; i < numMonitors; i++) {
5699 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005700 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005701 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5702 dump += "\n";
5703 }
5704}
5705
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005706class LooperEventCallback : public LooperCallback {
5707public:
5708 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5709 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5710
5711private:
5712 std::function<int(int events)> mCallback;
5713};
5714
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005715Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005716 if (DEBUG_CHANNEL_CREATION) {
5717 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005720 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005721 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005722 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005723
5724 if (result) {
5725 return base::Error(result) << "Failed to open input channel pair with name " << name;
5726 }
5727
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005729 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005730 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005731 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005732 std::shared_ptr<Connection> connection =
5733 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5734 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005736 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5737 ALOGE("Created a new connection, but the token %p is already known", token.get());
5738 }
5739 mConnectionsByToken.emplace(token, connection);
5740
5741 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5742 this, std::placeholders::_1, token);
5743
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005744 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5745 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746 } // release lock
5747
5748 // Wake the looper because some connections have changed.
5749 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005750 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751}
5752
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005753Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005754 const std::string& name,
5755 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005756 std::shared_ptr<InputChannel> serverChannel;
5757 std::unique_ptr<InputChannel> clientChannel;
5758 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5759 if (result) {
5760 return base::Error(result) << "Failed to open input channel pair with name " << name;
5761 }
5762
Michael Wright3dd60e22019-03-27 22:06:44 +00005763 { // acquire lock
5764 std::scoped_lock _l(mLock);
5765
5766 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005767 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5768 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005769 }
5770
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005771 std::shared_ptr<Connection> connection =
5772 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005773 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005774 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005775
5776 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5777 ALOGE("Created a new connection, but the token %p is already known", token.get());
5778 }
5779 mConnectionsByToken.emplace(token, connection);
5780 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5781 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005782
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005783 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005784
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005785 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5786 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005787 }
Garfield Tan15601662020-09-22 15:32:38 -07005788
Michael Wright3dd60e22019-03-27 22:06:44 +00005789 // Wake the looper because some connections have changed.
5790 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005791 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005792}
5793
Garfield Tan15601662020-09-22 15:32:38 -07005794status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005796 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797
Harry Cutts33476232023-01-30 19:57:29 +00005798 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799 if (status) {
5800 return status;
5801 }
5802 } // release lock
5803
5804 // Wake the poll loop because removing the connection may have changed the current
5805 // synchronization state.
5806 mLooper->wake();
5807 return OK;
5808}
5809
Garfield Tan15601662020-09-22 15:32:38 -07005810status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5811 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005812 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005813 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005814 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 return BAD_VALUE;
5816 }
5817
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005818 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005819
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005821 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822 }
5823
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005824 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825
5826 nsecs_t currentTime = now();
5827 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5828
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005829 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 return OK;
5831}
5832
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005833void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005834 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5835 auto& [displayId, monitors] = *it;
5836 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5837 return monitor.inputChannel->getConnectionToken() == connectionToken;
5838 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005839
Michael Wright3dd60e22019-03-27 22:06:44 +00005840 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005841 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005842 } else {
5843 ++it;
5844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 }
5846}
5847
Michael Wright3dd60e22019-03-27 22:06:44 +00005848status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005849 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005850 return pilferPointersLocked(token);
5851}
Michael Wright3dd60e22019-03-27 22:06:44 +00005852
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005853status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005854 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5855 if (!requestingChannel) {
5856 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5857 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005858 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005859
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005860 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005861 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005862 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5863 " Ignoring.");
5864 return BAD_VALUE;
5865 }
5866
5867 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005868 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005869 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005870 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005871 "input channel stole pointer stream");
5872 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005873 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005874 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005875 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005876 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005877 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005878 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005879 if (channel != nullptr && channel->getConnectionToken() != token) {
5880 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5881 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5882 canceledWindows += channel->getName();
5883 }
5884 }
5885 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5886 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5887 canceledWindows.c_str());
5888
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005889 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005890 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005891 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005892
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005893 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005894 return OK;
5895}
5896
Prabir Pradhan99987712020-11-10 18:43:05 -08005897void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5898 { // acquire lock
5899 std::scoped_lock _l(mLock);
5900 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005901 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005902 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5903 windowHandle != nullptr ? windowHandle->getName().c_str()
5904 : "token without window");
5905 }
5906
Vishnu Nairc519ff72021-01-21 08:23:08 -08005907 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005908 if (focusedToken != windowToken) {
5909 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5910 enabled ? "enable" : "disable");
5911 return;
5912 }
5913
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005914 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005915 ALOGW("Ignoring request to %s Pointer Capture: "
5916 "window has %s requested pointer capture.",
5917 enabled ? "enable" : "disable", enabled ? "already" : "not");
5918 return;
5919 }
5920
Christine Franksb768bb42021-11-29 12:11:31 -08005921 if (enabled) {
5922 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5923 mIneligibleDisplaysForPointerCapture.end(),
5924 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5925 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5926 return;
5927 }
5928 }
5929
Prabir Pradhan99987712020-11-10 18:43:05 -08005930 setPointerCaptureLocked(enabled);
5931 } // release lock
5932
5933 // Wake the thread to process command entries.
5934 mLooper->wake();
5935}
5936
Christine Franksb768bb42021-11-29 12:11:31 -08005937void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5938 { // acquire lock
5939 std::scoped_lock _l(mLock);
5940 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5941 if (!isEligible) {
5942 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5943 }
5944 } // release lock
5945}
5946
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005947std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5948 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005949 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005950 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005951 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005952 }
5953 }
5954 }
5955 return std::nullopt;
5956}
5957
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005958std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
5959 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005960 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005961 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005962 }
5963
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005964 for (const auto& [token, connection] : mConnectionsByToken) {
5965 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005966 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 }
5968 }
Robert Carr4e670e52018-08-15 13:26:12 -07005969
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005970 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971}
5972
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005973std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005974 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005975 if (connection == nullptr) {
5976 return "<nullptr>";
5977 }
5978 return connection->getInputChannelName();
5979}
5980
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005981void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005982 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005983 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005984}
5985
Prabir Pradhancef936d2021-07-21 16:17:52 +00005986void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005987 const std::shared_ptr<Connection>& connection,
5988 uint32_t seq, bool handled,
5989 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005990 // Handle post-event policy actions.
5991 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5992 if (dispatchEntryIt == connection->waitQueue.end()) {
5993 return;
5994 }
5995 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5996 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5997 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5998 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5999 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6000 }
6001 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6002 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6003 connection->inputChannel->getConnectionToken(),
6004 dispatchEntry->deliveryTime, consumeTime, finishTime);
6005 }
6006
6007 bool restartEvent;
6008 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6009 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6010 restartEvent =
6011 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6012 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6013 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6014 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6015 handled);
6016 } else {
6017 restartEvent = false;
6018 }
6019
6020 // Dequeue the event and start the next cycle.
6021 // Because the lock might have been released, it is possible that the
6022 // contents of the wait queue to have been drained, so we need to double-check
6023 // a few things.
6024 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6025 if (dispatchEntryIt != connection->waitQueue.end()) {
6026 dispatchEntry = *dispatchEntryIt;
6027 connection->waitQueue.erase(dispatchEntryIt);
6028 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6029 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6030 if (!connection->responsive) {
6031 connection->responsive = isConnectionResponsive(*connection);
6032 if (connection->responsive) {
6033 // The connection was unresponsive, and now it's responsive.
6034 processConnectionResponsiveLocked(*connection);
6035 }
6036 }
6037 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006038 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006039 connection->outboundQueue.push_front(dispatchEntry);
6040 traceOutboundQueueLength(*connection);
6041 } else {
6042 releaseDispatchEntry(dispatchEntry);
6043 }
6044 }
6045
6046 // Start the next dispatch cycle for this connection.
6047 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048}
6049
Prabir Pradhancef936d2021-07-21 16:17:52 +00006050void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6051 const sp<IBinder>& newToken) {
6052 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6053 scoped_unlock unlock(mLock);
6054 mPolicy->notifyFocusChanged(oldToken, newToken);
6055 };
6056 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057}
6058
Prabir Pradhancef936d2021-07-21 16:17:52 +00006059void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6060 auto command = [this, token, x, y]() REQUIRES(mLock) {
6061 scoped_unlock unlock(mLock);
6062 mPolicy->notifyDropWindow(token, x, y);
6063 };
6064 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006065}
6066
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006067void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006068 if (connection == nullptr) {
6069 LOG_ALWAYS_FATAL("Caller must check for nullness");
6070 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006071 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6072 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006073 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006074 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006075 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006076 return;
6077 }
6078 /**
6079 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6080 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6081 * has changed. This could cause newer entries to time out before the already dispatched
6082 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6083 * processes the events linearly. So providing information about the oldest entry seems to be
6084 * most useful.
6085 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006086 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006087 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6088 std::string reason =
6089 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006090 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006091 ns2ms(currentWait),
6092 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006093 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006094 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006095
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006096 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6097
6098 // Stop waking up for events on this connection, it is already unresponsive
6099 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006100}
6101
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006102void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6103 std::string reason =
6104 StringPrintf("%s does not have a focused window", application->getName().c_str());
6105 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006106
Prabir Pradhancef936d2021-07-21 16:17:52 +00006107 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6108 scoped_unlock unlock(mLock);
6109 mPolicy->notifyNoFocusedWindowAnr(application);
6110 };
6111 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006112}
6113
chaviw98318de2021-05-19 16:45:23 -05006114void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006115 const std::string& reason) {
6116 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6117 updateLastAnrStateLocked(windowLabel, reason);
6118}
6119
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006120void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6121 const std::string& reason) {
6122 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006123 updateLastAnrStateLocked(windowLabel, reason);
6124}
6125
6126void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6127 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006129 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130 struct tm tm;
6131 localtime_r(&t, &tm);
6132 char timestr[64];
6133 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006134 mLastAnrState.clear();
6135 mLastAnrState += INDENT "ANR:\n";
6136 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006137 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6138 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006139 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140}
6141
Prabir Pradhancef936d2021-07-21 16:17:52 +00006142void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6143 KeyEntry& entry) {
6144 const KeyEvent event = createKeyEvent(entry);
6145 nsecs_t delay = 0;
6146 { // release lock
6147 scoped_unlock unlock(mLock);
6148 android::base::Timer t;
6149 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6150 entry.policyFlags);
6151 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6152 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6153 std::to_string(t.duration().count()).c_str());
6154 }
6155 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156
6157 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006158 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006159 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006160 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006162 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006163 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006165}
6166
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006168 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006169 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006170 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006172 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006173 };
6174 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006175}
6176
Prabir Pradhanedd96402022-02-15 01:46:16 -08006177void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6178 std::optional<int32_t> pid) {
6179 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006180 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006181 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182 };
6183 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006184}
6185
6186/**
6187 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6188 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6189 * command entry to the command queue.
6190 */
6191void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6192 std::string reason) {
6193 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006194 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006195 if (connection.monitor) {
6196 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6197 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006198 pid = findMonitorPidByTokenLocked(connectionToken);
6199 } else {
6200 // The connection is a window
6201 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6202 reason.c_str());
6203 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6204 if (handle != nullptr) {
6205 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006206 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006207 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006208 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006209}
6210
6211/**
6212 * Tell the policy that a connection has become responsive so that it can stop ANR.
6213 */
6214void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6215 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006216 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006217 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006218 pid = findMonitorPidByTokenLocked(connectionToken);
6219 } else {
6220 // The connection is a window
6221 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6222 if (handle != nullptr) {
6223 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006224 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006225 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006226 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006227}
6228
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006229bool InputDispatcher::afterKeyEventLockedInterruptable(
6230 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6231 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006232 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006233 if (!handled) {
6234 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006235 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006236 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006237 return false;
6238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006240 // Get the fallback key state.
6241 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006242 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006243 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006244 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006245 connection->inputState.removeFallbackKey(originalKeyCode);
6246 }
6247
6248 if (handled || !dispatchEntry->hasForegroundTarget()) {
6249 // If the application handles the original key for which we previously
6250 // generated a fallback or if the window is not a foreground window,
6251 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006252 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006253 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006254 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6255 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6256 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6257 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6258 keyEntry.policyFlags);
6259 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006260 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006261 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262
6263 mLock.unlock();
6264
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006265 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006266 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267
6268 mLock.lock();
6269
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006270 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006271 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006272 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006273 "application handled the original non-fallback key "
6274 "or is no longer a foreground target, "
6275 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006276 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006279 connection->inputState.removeFallbackKey(originalKeyCode);
6280 }
6281 } else {
6282 // If the application did not handle a non-fallback key, first check
6283 // that we are in a good state to perform unhandled key event processing
6284 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006285 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006286 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006287 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6288 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6289 "since this is not an initial down. "
6290 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6291 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6292 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006293 return false;
6294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006296 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006297 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6298 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6299 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6300 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6301 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006302 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006303
6304 mLock.unlock();
6305
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006306 bool fallback =
6307 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006308 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006309
6310 mLock.lock();
6311
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006312 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006313 connection->inputState.removeFallbackKey(originalKeyCode);
6314 return false;
6315 }
6316
6317 // Latch the fallback keycode for this key on an initial down.
6318 // The fallback keycode cannot change at any other point in the lifecycle.
6319 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006321 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006322 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006323 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006324 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006325 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006326 }
6327
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006328 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006329
6330 // Cancel the fallback key if the policy decides not to send it anymore.
6331 // We will continue to dispatch the key to the policy but we will no
6332 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006333 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6334 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006335 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6336 if (fallback) {
6337 ALOGD("Unhandled key event: Policy requested to send key %d"
6338 "as a fallback for %d, but on the DOWN it had requested "
6339 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006340 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006341 } else {
6342 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6343 "but on the DOWN it had requested to send %d. "
6344 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006345 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006346 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006347 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006348
Michael Wrightfb04fd52022-11-24 22:31:11 +00006349 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006350 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006351 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006352 synthesizeCancelationEventsForConnectionLocked(connection, options);
6353
6354 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006355 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006356 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006357 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006358 }
6359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006361 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6362 {
6363 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006364 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006365 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006366 for (const auto& [key, value] : fallbackKeys) {
6367 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006368 }
6369 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6370 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006371 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006372 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006373
6374 if (fallback) {
6375 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006376 keyEntry.eventTime = event.getEventTime();
6377 keyEntry.deviceId = event.getDeviceId();
6378 keyEntry.source = event.getSource();
6379 keyEntry.displayId = event.getDisplayId();
6380 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006381 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006382 keyEntry.scanCode = event.getScanCode();
6383 keyEntry.metaState = event.getMetaState();
6384 keyEntry.repeatCount = event.getRepeatCount();
6385 keyEntry.downTime = event.getDownTime();
6386 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006387
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006388 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6389 ALOGD("Unhandled key event: Dispatching fallback key. "
6390 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006391 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006392 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006393 return true; // restart the event
6394 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006395 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6396 ALOGD("Unhandled key event: No fallback key.");
6397 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006398
6399 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006400 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 }
6402 }
6403 return false;
6404}
6405
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006406bool InputDispatcher::afterMotionEventLockedInterruptable(
6407 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6408 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409 return false;
6410}
6411
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412void InputDispatcher::traceInboundQueueLengthLocked() {
6413 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006414 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 }
6416}
6417
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006418void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419 if (ATRACE_ENABLED()) {
6420 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006421 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6422 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423 }
6424}
6425
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006426void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006427 if (ATRACE_ENABLED()) {
6428 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006429 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6430 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006431 }
6432}
6433
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006434void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006435 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006437 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 dumpDispatchStateLocked(dump);
6439
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006440 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006441 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006442 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006443 }
6444}
6445
6446void InputDispatcher::monitor() {
6447 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006448 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006449 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006450 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451}
6452
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006453/**
6454 * Wake up the dispatcher and wait until it processes all events and commands.
6455 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6456 * this method can be safely called from any thread, as long as you've ensured that
6457 * the work you are interested in completing has already been queued.
6458 */
6459bool InputDispatcher::waitForIdle() {
6460 /**
6461 * Timeout should represent the longest possible time that a device might spend processing
6462 * events and commands.
6463 */
6464 constexpr std::chrono::duration TIMEOUT = 100ms;
6465 std::unique_lock lock(mLock);
6466 mLooper->wake();
6467 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6468 return result == std::cv_status::no_timeout;
6469}
6470
Vishnu Naire798b472020-07-23 13:52:21 -07006471/**
6472 * Sets focus to the window identified by the token. This must be called
6473 * after updating any input window handles.
6474 *
6475 * Params:
6476 * request.token - input channel token used to identify the window that should gain focus.
6477 * request.focusedToken - the token that the caller expects currently to be focused. If the
6478 * specified token does not match the currently focused window, this request will be dropped.
6479 * If the specified focused token matches the currently focused window, the call will succeed.
6480 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6481 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6482 * when requesting the focus change. This determines which request gets
6483 * precedence if there is a focus change request from another source such as pointer down.
6484 */
Vishnu Nair958da932020-08-21 17:12:37 -07006485void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6486 { // acquire lock
6487 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006488 std::optional<FocusResolver::FocusChanges> changes =
6489 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6490 if (changes) {
6491 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006492 }
6493 } // release lock
6494 // Wake up poll loop since it may need to make new input dispatching choices.
6495 mLooper->wake();
6496}
6497
Vishnu Nairc519ff72021-01-21 08:23:08 -08006498void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6499 if (changes.oldFocus) {
6500 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006501 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006502 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006503 "focus left window");
6504 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006505 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006506 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006507 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006508 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006509 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006510 }
6511
Prabir Pradhan99987712020-11-10 18:43:05 -08006512 // If a window has pointer capture, then it must have focus. We need to ensure that this
6513 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6514 // If the window loses focus before it loses pointer capture, then the window can be in a state
6515 // where it has pointer capture but not focus, violating the contract. Therefore we must
6516 // dispatch the pointer capture event before the focus event. Since focus events are added to
6517 // the front of the queue (above), we add the pointer capture event to the front of the queue
6518 // after the focus events are added. This ensures the pointer capture event ends up at the
6519 // front.
6520 disablePointerCaptureForcedLocked();
6521
Vishnu Nairc519ff72021-01-21 08:23:08 -08006522 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006523 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006524 }
6525}
Vishnu Nair958da932020-08-21 17:12:37 -07006526
Prabir Pradhan99987712020-11-10 18:43:05 -08006527void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006528 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006529 return;
6530 }
6531
6532 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6533
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006534 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006535 setPointerCaptureLocked(false);
6536 }
6537
6538 if (!mWindowTokenWithPointerCapture) {
6539 // No need to send capture changes because no window has capture.
6540 return;
6541 }
6542
6543 if (mPendingEvent != nullptr) {
6544 // Move the pending event to the front of the queue. This will give the chance
6545 // for the pending event to be dropped if it is a captured event.
6546 mInboundQueue.push_front(mPendingEvent);
6547 mPendingEvent = nullptr;
6548 }
6549
6550 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006551 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006552 mInboundQueue.push_front(std::move(entry));
6553}
6554
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006555void InputDispatcher::setPointerCaptureLocked(bool enable) {
6556 mCurrentPointerCaptureRequest.enable = enable;
6557 mCurrentPointerCaptureRequest.seq++;
6558 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006559 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006560 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006561 };
6562 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006563}
6564
Vishnu Nair599f1412021-06-21 10:39:58 -07006565void InputDispatcher::displayRemoved(int32_t displayId) {
6566 { // acquire lock
6567 std::scoped_lock _l(mLock);
6568 // Set an empty list to remove all handles from the specific display.
6569 setInputWindowsLocked(/* window handles */ {}, displayId);
6570 setFocusedApplicationLocked(displayId, nullptr);
6571 // Call focus resolver to clean up stale requests. This must be called after input windows
6572 // have been removed for the removed display.
6573 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006574 // Reset pointer capture eligibility, regardless of previous state.
6575 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006576 // Remove the associated touch mode state.
6577 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006578 } // release lock
6579
6580 // Wake up poll loop since it may need to make new input dispatching choices.
6581 mLooper->wake();
6582}
6583
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006584void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6585 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006586 // The listener sends the windows as a flattened array. Separate the windows by display for
6587 // more convenient parsing.
6588 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006589 for (const auto& info : windowInfos) {
6590 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006591 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006592 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006593
6594 { // acquire lock
6595 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006596
6597 // Ensure that we have an entry created for all existing displays so that if a displayId has
6598 // no windows, we can tell that the windows were removed from the display.
6599 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6600 handlesPerDisplay[displayId];
6601 }
6602
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006603 mDisplayInfos.clear();
6604 for (const auto& displayInfo : displayInfos) {
6605 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6606 }
6607
6608 for (const auto& [displayId, handles] : handlesPerDisplay) {
6609 setInputWindowsLocked(handles, displayId);
6610 }
6611 }
6612 // Wake up poll loop since it may need to make new input dispatching choices.
6613 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006614}
6615
Vishnu Nair062a8672021-09-03 16:07:44 -07006616bool InputDispatcher::shouldDropInput(
6617 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006618 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6619 (windowHandle->getInfo()->inputConfig.test(
6620 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006621 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006622 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6623 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006624 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006625 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006626 windowHandle->getInfo()->displayId);
6627 return true;
6628 }
6629 return false;
6630}
6631
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006632void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6633 const std::vector<gui::WindowInfo>& windowInfos,
6634 const std::vector<DisplayInfo>& displayInfos) {
6635 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6636}
6637
Arthur Hungdfd528e2021-12-08 13:23:04 +00006638void InputDispatcher::cancelCurrentTouch() {
6639 {
6640 std::scoped_lock _l(mLock);
6641 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006642 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006643 "cancel current touch");
6644 synthesizeCancelationEventsForAllConnectionsLocked(options);
6645
6646 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006647 }
6648 // Wake up poll loop since there might be work to do.
6649 mLooper->wake();
6650}
6651
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006652void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6653 std::scoped_lock _l(mLock);
6654 mMonitorDispatchingTimeout = timeout;
6655}
6656
Arthur Hungc539dbb2022-12-08 07:45:36 +00006657void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6658 const sp<WindowInfoHandle>& oldWindowHandle,
6659 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006660 TouchState& state, int32_t pointerId,
6661 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006662 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6663 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006664 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6665 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6666 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6667 newWindowHandle->getInfo()->inputConfig.test(
6668 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6669 const sp<WindowInfoHandle> oldWallpaper =
6670 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6671 const sp<WindowInfoHandle> newWallpaper =
6672 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6673 if (oldWallpaper == newWallpaper) {
6674 return;
6675 }
6676
6677 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006678 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6679 addWindowTargetLocked(oldWallpaper,
6680 oldTouchedWindow.targetFlags |
6681 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6682 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6683 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006684 }
6685
6686 if (newWallpaper != nullptr) {
6687 state.addOrUpdateWindow(newWallpaper,
6688 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6689 InputTarget::Flags::WINDOW_IS_OBSCURED |
6690 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6691 pointerIds);
6692 }
6693}
6694
6695void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6696 ftl::Flags<InputTarget::Flags> newTargetFlags,
6697 const sp<WindowInfoHandle> fromWindowHandle,
6698 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006699 TouchState& state,
6700 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006701 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6702 fromWindowHandle->getInfo()->inputConfig.test(
6703 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6704 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6705 toWindowHandle->getInfo()->inputConfig.test(
6706 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6707
6708 const sp<WindowInfoHandle> oldWallpaper =
6709 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6710 const sp<WindowInfoHandle> newWallpaper =
6711 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6712 if (oldWallpaper == newWallpaper) {
6713 return;
6714 }
6715
6716 if (oldWallpaper != nullptr) {
6717 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6718 "transferring touch focus to another window");
6719 state.removeWindowByToken(oldWallpaper->getToken());
6720 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6721 }
6722
6723 if (newWallpaper != nullptr) {
6724 nsecs_t downTimeInTarget = now();
6725 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6726 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6727 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6728 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6729 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006730 std::shared_ptr<Connection> wallpaperConnection =
6731 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006732 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006733 std::shared_ptr<Connection> toConnection =
6734 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006735 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6736 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6737 wallpaperFlags);
6738 }
6739 }
6740}
6741
6742sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6743 const sp<WindowInfoHandle>& windowHandle) const {
6744 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6745 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6746 bool foundWindow = false;
6747 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6748 if (!foundWindow && otherHandle != windowHandle) {
6749 continue;
6750 }
6751 if (windowHandle == otherHandle) {
6752 foundWindow = true;
6753 continue;
6754 }
6755
6756 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6757 return otherHandle;
6758 }
6759 }
6760 return nullptr;
6761}
6762
Garfield Tane84e6f92019-08-29 17:28:41 -07006763} // namespace android::inputdispatcher