blob: 12ac77cc5a4eeaa402e37b388ee85fde678adae2 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000034#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000048#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070049#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#define INDENT " "
52#define INDENT2 " "
53#define INDENT3 " "
54#define INDENT4 " "
55
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080056using namespace android::ftl::flag_operators;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -070057using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080058using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000059using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070061using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050062using android::gui::FocusRequest;
63using android::gui::TouchOcclusionMode;
64using android::gui::WindowInfo;
65using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080066using android::os::InputEventInjectionResult;
67using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068
Garfield Tane84e6f92019-08-29 17:28:41 -070069namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Prabir Pradhancef936d2021-07-21 16:17:52 +000071namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000072// Temporarily releases a held mutex for the lifetime of the instance.
73// Named to match std::scoped_lock
74class scoped_unlock {
75public:
76 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
77 ~scoped_unlock() { mMutex.lock(); }
78
79private:
80 std::mutex& mMutex;
81};
82
Michael Wrightd02c5b62014-02-10 15:10:22 -080083// Default input dispatching timeout if there is no focused application or paused window
84// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080085const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
86 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
87 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow for all pending events to be processed when an app switch
90// key is on the way. This is used to preempt input dispatch and drop input events
91// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080094const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Michael Wrightd02c5b62014-02-10 15:10:22 -080096// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000097constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
98
99// Log a warning when an interception call takes longer than this to process.
100constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700102// Additional key latency in case a connection is still processing some motion events.
103// This will help with the case when a user touched a button that opens a new window,
104// and gives us the chance to dispatch the key to this new window.
105constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000108constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
109
Antonio Kantekea47acb2021-12-23 12:41:25 -0800110// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111constexpr int LOGTAG_INPUT_INTERACTION = 62000;
112constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000113constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000114
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000115const ui::Transform kIdentityTransform;
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118 return systemTime(SYSTEM_TIME_MONOTONIC);
119}
120
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700121inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000122 if (binder == nullptr) {
123 return "<null>";
124 }
125 return StringPrintf("%p", binder.get());
126}
127
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000128inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700129 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
130 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131}
132
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700133Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 case AKEY_EVENT_ACTION_DOWN:
136 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700137 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700139 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 }
141}
142
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700143Result<void> validateKeyEvent(int32_t action) {
144 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145}
146
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700147Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800148 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700150 case AMOTION_EVENT_ACTION_UP: {
151 if (pointerCount != 1) {
152 return Error() << "invalid pointer count " << pointerCount;
153 }
154 return {};
155 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
160 if (pointerCount < 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700168 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 case AMOTION_EVENT_ACTION_POINTER_DOWN:
170 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800171 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700172 if (index < 0) {
173 return Error() << "invalid index " << index << " for "
174 << MotionEvent::actionToString(action);
175 }
176 if (index >= pointerCount) {
177 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
178 }
179 if (pointerCount <= 1) {
180 return Error() << "invalid pointer count " << pointerCount << " for "
181 << MotionEvent::actionToString(action);
182 }
183 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 }
185 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700186 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
187 if (actionButton == 0) {
188 return Error() << "action button should be nonzero for "
189 << MotionEvent::actionToString(action);
190 }
191 return {};
192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700194 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 }
196}
197
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000198int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500199 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
200}
201
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700202Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
203 const PointerProperties* pointerProperties) {
204 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
205 if (!actionCheck.ok()) {
206 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 }
208 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700209 return Error() << "Motion event has invalid pointer count " << pointerCount
210 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800212 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 for (size_t i = 0; i < pointerCount; i++) {
214 int32_t id = pointerProperties[i].id;
215 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700216 return Error() << "Motion event has invalid pointer id " << id
217 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800219 if (pointerIdBits.test(id)) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700220 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800222 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700224 return {};
225}
226
227Result<void> validateInputEvent(const InputEvent& event) {
228 switch (event.getType()) {
229 case InputEventType::KEY: {
230 const KeyEvent& key = static_cast<const KeyEvent&>(event);
231 const int32_t action = key.getAction();
232 return validateKeyEvent(action);
233 }
234 case InputEventType::MOTION: {
235 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
236 const int32_t action = motion.getAction();
237 const size_t pointerCount = motion.getPointerCount();
238 const PointerProperties* pointerProperties = motion.getPointerProperties();
239 const int32_t actionButton = motion.getActionButton();
240 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
241 }
242 default: {
243 return {};
244 }
245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246}
247
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000248std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000250 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 }
252
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000253 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 bool first = true;
255 Region::const_iterator cur = region.begin();
256 Region::const_iterator const tail = region.end();
257 while (cur != tail) {
258 if (first) {
259 first = false;
260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800261 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800263 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 cur++;
265 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000266 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267}
268
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500270 constexpr size_t maxEntries = 50; // max events to print
271 constexpr size_t skipBegin = maxEntries / 2;
272 const size_t skipEnd = queue.size() - maxEntries / 2;
273 // skip from maxEntries / 2 ... size() - maxEntries/2
274 // only print from 0 .. skipBegin and then from skipEnd .. size()
275
276 std::string dump;
277 for (size_t i = 0; i < queue.size(); i++) {
278 const DispatchEntry& entry = *queue[i];
279 if (i >= skipBegin && i < skipEnd) {
280 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
281 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
282 continue;
283 }
284 dump.append(INDENT4);
285 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800286 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
287 "ms",
288 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500289 ns2ms(currentTime - entry.eventEntry->eventTime));
290 if (entry.deliveryTime != 0) {
291 // This entry was delivered, so add information on how long we've been waiting
292 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
293 }
294 dump.append("\n");
295 }
296 return dump;
297}
298
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700299/**
300 * Find the entry in std::unordered_map by key, and return it.
301 * If the entry is not found, return a default constructed entry.
302 *
303 * Useful when the entries are vectors, since an empty vector will be returned
304 * if the entry is not found.
305 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
306 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700307template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000308V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700309 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700310 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800311}
312
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700314 if (first == second) {
315 return true;
316 }
317
318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321
322 return first->getToken() == second->getToken();
323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329 return first->applicationInfo.token != nullptr &&
330 first->applicationInfo.token == second->applicationInfo.token;
331}
332
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800333template <typename T>
334size_t firstMarkedBit(T set) {
335 // TODO: replace with std::countr_zero from <bit> when that's available
336 LOG_ALWAYS_FATAL_IF(set.none());
337 size_t i = 0;
338 while (!set.test(i)) {
339 i++;
340 }
341 return i;
342}
343
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800344std::unique_ptr<DispatchEntry> createDispatchEntry(
345 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
346 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 if (inputTarget.useDefaultPointerTransform()) {
348 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700349 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700350 inputTarget.displayTransform,
351 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 }
353
354 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
355 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 std::vector<PointerCoords> pointerCoords;
358 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 // Use the first pointer information to normalize all other pointers. This could be any pointer
361 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 // uses the transform for the normalized pointer.
363 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800364 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 // Iterate through all pointers in the event to normalize against the first.
368 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
369 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
370 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700374 // First, apply the current pointer's transform to update the coordinates into
375 // window space.
376 pointerCoords[pointerIndex].transform(currTransform);
377 // Next, apply the inverse transform of the normalized coordinates so the
378 // current coordinates are transformed into the normalized coordinate space.
379 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380 }
381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700382 std::unique_ptr<MotionEntry> combinedMotionEntry =
383 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
384 motionEntry.deviceId, motionEntry.source,
385 motionEntry.displayId, motionEntry.policyFlags,
386 motionEntry.action, motionEntry.actionButton,
387 motionEntry.flags, motionEntry.metaState,
388 motionEntry.buttonState, motionEntry.classification,
389 motionEntry.edgeFlags, motionEntry.xPrecision,
390 motionEntry.yPrecision, motionEntry.xCursorPosition,
391 motionEntry.yCursorPosition, motionEntry.downTime,
392 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000393 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000394
395 if (motionEntry.injectionState) {
396 combinedMotionEntry->injectionState = motionEntry.injectionState;
397 combinedMotionEntry->injectionState->refCount += 1;
398 }
399
400 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700401 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700402 firstPointerTransform, inputTarget.displayTransform,
403 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404 return dispatchEntry;
405}
406
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000407status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
408 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700409 std::unique_ptr<InputChannel> uniqueServerChannel;
410 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
411
412 serverChannel = std::move(uniqueServerChannel);
413 return result;
414}
415
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500416template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000417bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500418 if (lhs == nullptr && rhs == nullptr) {
419 return true;
420 }
421 if (lhs == nullptr || rhs == nullptr) {
422 return false;
423 }
424 return *lhs == *rhs;
425}
426
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000427KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000428 KeyEvent event;
429 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
430 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
431 entry.repeatCount, entry.downTime, entry.eventTime);
432 return event;
433}
434
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000436 // Do not keep track of gesture monitors. They receive every event and would disproportionately
437 // affect the statistics.
438 if (connection.monitor) {
439 return false;
440 }
441 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
442 if (!connection.responsive) {
443 return false;
444 }
445 return true;
446}
447
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000448bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000449 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
450 const int32_t& inputEventId = eventEntry.id;
451 if (inputEventId != dispatchEntry.resolvedEventId) {
452 // Event was transmuted
453 return false;
454 }
455 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
456 return false;
457 }
458 // Only track latency for events that originated from hardware
459 if (eventEntry.isSynthesized()) {
460 return false;
461 }
462 const EventEntry::Type& inputEventEntryType = eventEntry.type;
463 if (inputEventEntryType == EventEntry::Type::KEY) {
464 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
465 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
466 return false;
467 }
468 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
469 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
470 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
471 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
472 return false;
473 }
474 } else {
475 // Not a key or a motion
476 return false;
477 }
478 if (!shouldReportMetricsForConnection(connection)) {
479 return false;
480 }
481 return true;
482}
483
Prabir Pradhancef936d2021-07-21 16:17:52 +0000484/**
485 * Connection is responsive if it has no events in the waitQueue that are older than the
486 * current time.
487 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000488bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000489 const nsecs_t currentTime = now();
490 for (const DispatchEntry* entry : connection.waitQueue) {
491 if (entry->timeoutTime < currentTime) {
492 return false;
493 }
494 }
495 return true;
496}
497
Antonio Kantekf16f2832021-09-28 04:39:20 +0000498// Returns true if the event type passed as argument represents a user activity.
499bool isUserActivityEvent(const EventEntry& eventEntry) {
500 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000501 case EventEntry::Type::CONFIGURATION_CHANGED:
502 case EventEntry::Type::DEVICE_RESET:
503 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000504 case EventEntry::Type::FOCUS:
505 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000506 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000507 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000509 case EventEntry::Type::KEY:
510 case EventEntry::Type::MOTION:
511 return true;
512 }
513}
514
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800515// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000516bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000517 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800518 const auto inputConfig = windowInfo.inputConfig;
519 if (windowInfo.displayId != displayId ||
520 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800521 return false;
522 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700523 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800524 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800525 return false;
526 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000527
528 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
529 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
530 // the window. Points on the right and bottom edges should not be inside the window, so we need
531 // to be careful about performing a hit test when the display is rotated, since the "right" and
532 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
533 // logical display in which WM determined the bounds. Perform the hit test in the logical
534 // display space to ensure these edges are considered correctly in all orientations.
535 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
536 const auto p = displayTransform.transform(x, y);
537 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800538 return false;
539 }
540 return true;
541}
542
Prabir Pradhand65552b2021-10-07 11:23:50 -0700543bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
544 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000545 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700546}
547
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800548// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000549// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
550// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
551// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800552// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000553bool canReceiveForegroundTouches(const WindowInfo& info) {
554 // A non-touchable window can still receive touch events (e.g. in the case of
555 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
556 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
557}
558
Antonio Kantek48710e42022-03-24 14:19:30 -0700559bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
560 if (windowHandle == nullptr) {
561 return false;
562 }
563 const WindowInfo* windowInfo = windowHandle->getInfo();
564 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
565 return true;
566 }
567 return false;
568}
569
Prabir Pradhan5735a322022-04-11 17:23:34 +0000570// Checks targeted injection using the window's owner's uid.
571// Returns an empty string if an entry can be sent to the given window, or an error message if the
572// entry is a targeted injection whose uid target doesn't match the window owner.
573std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
574 const EventEntry& entry) {
575 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
576 // The event was not injected, or the injected event does not target a window.
577 return {};
578 }
579 const int32_t uid = *entry.injectionState->targetUid;
580 if (window == nullptr) {
581 return StringPrintf("No valid window target for injection into uid %d.", uid);
582 }
583 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
584 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
585 "owned by uid %d.",
586 uid, window->getName().c_str(), window->getInfo()->ownerUid);
587 }
588 return {};
589}
590
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000591std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700592 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
593 // Always dispatch mouse events to cursor position.
594 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000595 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700596 }
597
598 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000599 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
600 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700601}
602
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700603std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
604 if (eventEntry.type == EventEntry::Type::KEY) {
605 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
606 return keyEntry.downTime;
607 } else if (eventEntry.type == EventEntry::Type::MOTION) {
608 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
609 return motionEntry.downTime;
610 }
611 return std::nullopt;
612}
613
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000614/**
615 * Compare the old touch state to the new touch state, and generate the corresponding touched
616 * windows (== input targets).
617 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
618 * If the pointer just entered the new window, produce HOVER_ENTER.
619 * For pointers remaining in the window, produce HOVER_MOVE.
620 */
621std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
622 const TouchState& newTouchState,
623 const MotionEntry& entry) {
624 std::vector<TouchedWindow> out;
625 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
626 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
627 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
628 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
629 // Not a hover event - don't need to do anything
630 return out;
631 }
632
633 // We should consider all hovering pointers here. But for now, just use the first one
634 const int32_t pointerId = entry.pointerProperties[0].id;
635
636 std::set<sp<WindowInfoHandle>> oldWindows;
637 if (oldState != nullptr) {
638 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
639 }
640
641 std::set<sp<WindowInfoHandle>> newWindows =
642 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
643
644 // If the pointer is no longer in the new window set, send HOVER_EXIT.
645 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
646 if (newWindows.find(oldWindow) == newWindows.end()) {
647 TouchedWindow touchedWindow;
648 touchedWindow.windowHandle = oldWindow;
649 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800650 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000651 out.push_back(touchedWindow);
652 }
653 }
654
655 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
656 TouchedWindow touchedWindow;
657 touchedWindow.windowHandle = newWindow;
658 if (oldWindows.find(newWindow) == oldWindows.end()) {
659 // Any windows that have this pointer now, and didn't have it before, should get
660 // HOVER_ENTER
661 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
662 } else {
663 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700664 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
665 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
666 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000667 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
668 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800669 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000670 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
671 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
672 }
673 out.push_back(touchedWindow);
674 }
675 return out;
676}
677
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800678template <typename T>
679std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
680 left.insert(left.end(), right.begin(), right.end());
681 return left;
682}
683
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000684} // namespace
685
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686// --- InputDispatcher ---
687
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}
719
720InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000721 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722
Prabir Pradhancef936d2021-07-21 16:17:52 +0000723 resetKeyRepeatLocked();
724 releasePendingEventLocked();
725 drainInboundQueueLocked();
726 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000728 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700729 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000730 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 }
732}
733
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700734status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700735 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700736 return ALREADY_EXISTS;
737 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700738 mThread = std::make_unique<InputThread>(
739 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
740 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700741}
742
743status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700744 if (mThread && mThread->isCallingThread()) {
745 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700746 return INVALID_OPERATION;
747 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700748 mThread.reset();
749 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700750}
751
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700753 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800755 std::scoped_lock _l(mLock);
756 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757
758 // Run a dispatch loop if there are no pending commands.
759 // The dispatch loop might enqueue commands to run afterwards.
760 if (!haveCommandsLocked()) {
761 dispatchOnceInnerLocked(&nextWakeupTime);
762 }
763
764 // Run all pending commands if there are any.
765 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000766 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700767 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800769
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700770 // If we are still waiting for ack on some events,
771 // we might have to wake up earlier to check if an app is anr'ing.
772 const nsecs_t nextAnrCheck = processAnrsLocked();
773 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
774
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800775 // We are about to enter an infinitely long sleep, because we have no commands or
776 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700777 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800778 mDispatcherEnteredIdle.notify_all();
779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 } // release lock
781
782 // Wait for callback or timeout or wake. (make sure we round up, not down)
783 nsecs_t currentTime = now();
784 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
785 mLooper->pollOnce(timeoutMillis);
786}
787
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700788/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500789 * Raise ANR if there is no focused window.
790 * Before the ANR is raised, do a final state check:
791 * 1. The currently focused application must be the same one we are waiting for.
792 * 2. Ensure we still don't have a focused window.
793 */
794void InputDispatcher::processNoFocusedWindowAnrLocked() {
795 // Check if the application that we are waiting for is still focused.
796 std::shared_ptr<InputApplicationHandle> focusedApplication =
797 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
798 if (focusedApplication == nullptr ||
799 focusedApplication->getApplicationToken() !=
800 mAwaitedFocusedApplication->getApplicationToken()) {
801 // Unexpected because we should have reset the ANR timer when focused application changed
802 ALOGE("Waited for a focused window, but focused application has already changed to %s",
803 focusedApplication->getName().c_str());
804 return; // The focused application has changed.
805 }
806
chaviw98318de2021-05-19 16:45:23 -0500807 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500808 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
809 if (focusedWindowHandle != nullptr) {
810 return; // We now have a focused window. No need for ANR.
811 }
812 onAnrLocked(mAwaitedFocusedApplication);
813}
814
815/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816 * Check if any of the connections' wait queues have events that are too old.
817 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
818 * Return the time at which we should wake up next.
819 */
820nsecs_t InputDispatcher::processAnrsLocked() {
821 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700822 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700823 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
824 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
825 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500826 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700827 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500828 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700829 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500831 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700832 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
833 }
834 }
835
836 // Check if any connection ANRs are due
837 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
838 if (currentTime < nextAnrCheck) { // most likely scenario
839 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
840 }
841
842 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700843 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700844 if (connection == nullptr) {
845 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
846 return nextAnrCheck;
847 }
848 connection->responsive = false;
849 // Stop waking up for this unresponsive connection
850 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000851 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700852 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700853}
854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800855std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700856 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800857 if (connection->monitor) {
858 return mMonitorDispatchingTimeout;
859 }
860 const sp<WindowInfoHandle> window =
861 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700862 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500863 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700864 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500865 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700866}
867
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
869 nsecs_t currentTime = now();
870
Jeff Browndc5992e2014-04-11 01:27:26 -0700871 // Reset the key repeat timer whenever normal dispatch is suspended while the
872 // device is in a non-interactive state. This is to ensure that we abort a key
873 // repeat if the device is just coming out of sleep.
874 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 resetKeyRepeatLocked();
876 }
877
878 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
879 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100880 if (DEBUG_FOCUS) {
881 ALOGD("Dispatch frozen. Waiting some more.");
882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 return;
884 }
885
886 // Optimize latency of app switches.
887 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
888 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
889 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
890 if (mAppSwitchDueTime < *nextWakeupTime) {
891 *nextWakeupTime = mAppSwitchDueTime;
892 }
893
894 // Ready to start a new event.
895 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700897 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 if (isAppSwitchDue) {
899 // The inbound queue is empty so the app switch key we were waiting
900 // for will never arrive. Stop waiting for it.
901 resetPendingAppSwitchLocked(false);
902 isAppSwitchDue = false;
903 }
904
905 // Synthesize a key repeat if appropriate.
906 if (mKeyRepeatState.lastKeyEntry) {
907 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
908 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
909 } else {
910 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
911 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
912 }
913 }
914 }
915
916 // Nothing to do if there is no pending event.
917 if (!mPendingEvent) {
918 return;
919 }
920 } else {
921 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700922 mPendingEvent = mInboundQueue.front();
923 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 traceInboundQueueLengthLocked();
925 }
926
927 // Poke user activity for this event.
928 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
932
933 // Now we have an event to dispatch.
934 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700935 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700937 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700939 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700941 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 }
943
944 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700945 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 }
947
948 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700949 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700950 const ConfigurationChangedEntry& typedEntry =
951 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 break;
955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700957 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700958 const DeviceResetEntry& typedEntry =
959 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700961 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 break;
963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100965 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700966 std::shared_ptr<FocusEntry> typedEntry =
967 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100968 dispatchFocusLocked(currentTime, typedEntry);
969 done = true;
970 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
971 break;
972 }
973
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700974 case EventEntry::Type::TOUCH_MODE_CHANGED: {
975 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
976 dispatchTouchModeChangeLocked(currentTime, typedEntry);
977 done = true;
978 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
979 break;
980 }
981
Prabir Pradhan99987712020-11-10 18:43:05 -0800982 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
983 const auto typedEntry =
984 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
985 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
986 done = true;
987 break;
988 }
989
arthurhungb89ccb02020-12-30 16:19:01 +0800990 case EventEntry::Type::DRAG: {
991 std::shared_ptr<DragEntry> typedEntry =
992 std::static_pointer_cast<DragEntry>(mPendingEvent);
993 dispatchDragLocked(currentTime, typedEntry);
994 done = true;
995 break;
996 }
997
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700998 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001001 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 resetPendingAppSwitchLocked(true);
1003 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 } else if (dropReason == DropReason::NOT_DROPPED) {
1005 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 }
1007 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001008 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1012 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001014 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 break;
1016 }
1017
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001019 std::shared_ptr<MotionEntry> motionEntry =
1020 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1022 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001024 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001025 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001027 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1028 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001030 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
Chris Yef59a2f42020-10-16 12:55:26 -07001033
1034 case EventEntry::Type::SENSOR: {
1035 std::shared_ptr<SensorEntry> sensorEntry =
1036 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1037 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1038 dropReason = DropReason::APP_SWITCH;
1039 }
1040 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1041 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1042 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1043 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1044 dropReason = DropReason::STALE;
1045 }
1046 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1047 done = true;
1048 break;
1049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
1051
1052 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001054 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
Michael Wright3a981722015-06-10 15:26:13 +01001056 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057
1058 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001059 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
1061}
1062
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001063bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1064 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1065}
1066
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001067/**
1068 * Return true if the events preceding this incoming motion event should be dropped
1069 * Return false otherwise (the default behaviour)
1070 */
1071bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001072 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001073 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001074
1075 // Optimize case where the current application is unresponsive and the user
1076 // decides to touch a window in a different application.
1077 // If the application takes too long to catch up then we drop all events preceding
1078 // the touch into the other window.
1079 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001080 const int32_t displayId = motionEntry.displayId;
1081 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001082 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001083
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001084 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001085 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001086 touchedWindowHandle->getApplicationToken() !=
1087 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001088 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001089 ALOGI("Pruning input queue because user touched a different application while waiting "
1090 "for %s",
1091 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092 return true;
1093 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001094
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001095 // Alternatively, maybe there's a spy window that could handle this event.
1096 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1097 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1098 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001099 const std::shared_ptr<Connection> connection =
1100 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001101 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001102 // This spy window could take more input. Drop all events preceding this
1103 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001104 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001105 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001106 mAwaitedFocusedApplication->getName().c_str());
1107 return true;
1108 }
1109 }
1110 }
1111
1112 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1113 // yet been processed by some connections, the dispatcher will wait for these motion
1114 // events to be processed before dispatching the key event. This is because these motion events
1115 // may cause a new window to be launched, which the user might expect to receive focus.
1116 // To prevent waiting forever for such events, just send the key to the currently focused window
1117 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1118 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1119 "just send the pending key event to the focused window.");
1120 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001121 }
1122 return false;
1123}
1124
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001125bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001126 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001127 mInboundQueue.push_back(std::move(newEntry));
1128 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 traceInboundQueueLengthLocked();
1130
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001131 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001133 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1134 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 // Optimize app switch latency.
1136 // If the application takes too long to catch up then we drop all events preceding
1137 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001138 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001140 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001142 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001144 if (DEBUG_APP_SWITCH) {
1145 ALOGD("App switch is pending!");
1146 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001147 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 mAppSwitchSawKeyDown = false;
1149 needWake = true;
1150 }
1151 }
1152 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001153
1154 // If a new up event comes in, and the pending event with same key code has been asked
1155 // to try again later because of the policy. We have to reset the intercept key wake up
1156 // time for it may have been handled in the policy and could be dropped.
1157 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1158 mPendingEvent->type == EventEntry::Type::KEY) {
1159 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1160 if (pendingKey.keyCode == keyEntry.keyCode &&
1161 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001162 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1163 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001164 pendingKey.interceptKeyWakeupTime = 0;
1165 needWake = true;
1166 }
1167 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 break;
1169 }
1170
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001171 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001172 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1173 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1175 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001176 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001180 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001181 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1182 break;
1183 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001184 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001185 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001186 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001187 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001188 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1189 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001190 // nothing to do
1191 break;
1192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194
1195 return needWake;
1196}
1197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001199 // Do not store sensor event in recent queue to avoid flooding the queue.
1200 if (entry->type != EventEntry::Type::SENSOR) {
1201 mRecentQueue.push_back(entry);
1202 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001204 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206}
1207
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001208std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001209InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001210 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001212 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001213 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001214 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001215 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001216 continue;
1217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001219 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001220 if (!info.isSpy() &&
1221 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001222 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001223 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001224
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001225 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1226 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001227 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001228 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001231 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232}
1233
Prabir Pradhand65552b2021-10-07 11:23:50 -07001234std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001235 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001236 // Traverse windows from front to back and gather the touched spy windows.
1237 std::vector<sp<WindowInfoHandle>> spyWindows;
1238 const auto& windowHandles = getWindowHandlesLocked(displayId);
1239 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1240 const WindowInfo& info = *windowHandle->getInfo();
1241
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001242 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001243 continue;
1244 }
1245 if (!info.isSpy()) {
1246 // The first touched non-spy window was found, so return the spy windows touched so far.
1247 return spyWindows;
1248 }
1249 spyWindows.push_back(windowHandle);
1250 }
1251 return spyWindows;
1252}
1253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001254void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 const char* reason;
1256 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001257 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001258 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001259 ALOGD("Dropped event because policy consumed it.");
1260 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 reason = "inbound event was dropped because the policy consumed it";
1262 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001263 case DropReason::DISABLED:
1264 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 ALOGI("Dropped event because input dispatch is disabled.");
1266 }
1267 reason = "inbound event was dropped because input dispatch is disabled";
1268 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001269 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 ALOGI("Dropped event because of pending overdue app switch.");
1271 reason = "inbound event was dropped because of pending overdue app switch";
1272 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001273 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001274 ALOGI("Dropped event because the current application is not responding and the user "
1275 "has started interacting with a different application.");
1276 reason = "inbound event was dropped because the current application is not responding "
1277 "and the user has started interacting with a different application";
1278 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001279 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 ALOGI("Dropped event because it is stale.");
1281 reason = "inbound event was dropped because it is stale";
1282 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001283 case DropReason::NO_POINTER_CAPTURE:
1284 ALOGI("Dropped event because there is no window with Pointer Capture.");
1285 reason = "inbound event was dropped because there is no window with Pointer Capture";
1286 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001287 case DropReason::NOT_DROPPED: {
1288 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 }
1292
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001293 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001294 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001295 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001299 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001300 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1301 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001302 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 synthesizeCancelationEventsForAllConnectionsLocked(options);
1304 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001305 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1306 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 synthesizeCancelationEventsForAllConnectionsLocked(options);
1308 }
1309 break;
1310 }
Chris Yef59a2f42020-10-16 12:55:26 -07001311 case EventEntry::Type::SENSOR: {
1312 break;
1313 }
arthurhungb89ccb02020-12-30 16:19:01 +08001314 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1315 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 break;
1317 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001318 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001319 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001320 case EventEntry::Type::CONFIGURATION_CHANGED:
1321 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001322 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001323 break;
1324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
1326}
1327
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001328static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1330 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331}
1332
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001333bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1334 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1335 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1336 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337}
1338
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001339bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001340 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341}
1342
1343void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001344 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001346 if (DEBUG_APP_SWITCH) {
1347 if (handled) {
1348 ALOGD("App switch has arrived.");
1349 } else {
1350 ALOGD("App switch was abandoned.");
1351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353}
1354
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001356 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357}
1358
Prabir Pradhancef936d2021-07-21 16:17:52 +00001359bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001360 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 return false;
1362 }
1363
1364 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001365 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001366 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001367 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1368 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001369 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 return true;
1371}
1372
Prabir Pradhancef936d2021-07-21 16:17:52 +00001373void InputDispatcher::postCommandLocked(Command&& command) {
1374 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375}
1376
1377void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001378 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001379 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001380 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 releaseInboundEventLocked(entry);
1382 }
1383 traceInboundQueueLengthLocked();
1384}
1385
1386void InputDispatcher::releasePendingEventLocked() {
1387 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001389 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
1391}
1392
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001393void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001395 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001396 if (DEBUG_DISPATCH_CYCLE) {
1397 ALOGD("Injected inbound event was dropped.");
1398 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001399 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 }
1401 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001402 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 }
1404 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405}
1406
1407void InputDispatcher::resetKeyRepeatLocked() {
1408 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001409 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411}
1412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001413std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1414 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415
Michael Wright2e732952014-09-24 13:26:59 -07001416 uint32_t policyFlags = entry->policyFlags &
1417 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419 std::shared_ptr<KeyEntry> newEntry =
1420 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1421 entry->source, entry->displayId, policyFlags, entry->action,
1422 entry->flags, entry->keyCode, entry->scanCode,
1423 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001425 newEntry->syntheticRepeat = true;
1426 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001428 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001432 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001433 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1434 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436
1437 // Reset key repeating in case a keyboard device was added or removed or something.
1438 resetKeyRepeatLocked();
1439
1440 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001441 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1442 scoped_unlock unlock(mLock);
1443 mPolicy->notifyConfigurationChanged(eventTime);
1444 };
1445 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 return true;
1447}
1448
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001449bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1450 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001451 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1452 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1453 entry.deviceId);
1454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455
liushenxiang42232912021-05-21 20:24:09 +08001456 // Reset key repeating in case a keyboard device was disabled or enabled.
1457 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1458 resetKeyRepeatLocked();
1459 }
1460
Michael Wrightfb04fd52022-11-24 22:31:11 +00001461 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001462 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 synthesizeCancelationEventsForAllConnectionsLocked(options);
1464 return true;
1465}
1466
Vishnu Nairad321cd2020-08-20 16:40:21 -07001467void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001468 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001469 if (mPendingEvent != nullptr) {
1470 // Move the pending event to the front of the queue. This will give the chance
1471 // for the pending event to get dispatched to the newly focused window
1472 mInboundQueue.push_front(mPendingEvent);
1473 mPendingEvent = nullptr;
1474 }
1475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001476 std::unique_ptr<FocusEntry> focusEntry =
1477 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1478 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001479
1480 // This event should go to the front of the queue, but behind all other focus events
1481 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001483 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001484 [](const std::shared_ptr<EventEntry>& event) {
1485 return event->type == EventEntry::Type::FOCUS;
1486 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001487
1488 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001489 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001490}
1491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001492void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001493 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001494 if (channel == nullptr) {
1495 return; // Window has gone away
1496 }
1497 InputTarget target;
1498 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001499 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001500 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001501 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1502 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001503 std::string reason = std::string("reason=").append(entry->reason);
1504 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001505 dispatchEventLocked(currentTime, entry, {target});
1506}
1507
Prabir Pradhan99987712020-11-10 18:43:05 -08001508void InputDispatcher::dispatchPointerCaptureChangedLocked(
1509 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1510 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001511 dropReason = DropReason::NOT_DROPPED;
1512
Prabir Pradhan99987712020-11-10 18:43:05 -08001513 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001514 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001515
1516 if (entry->pointerCaptureRequest.enable) {
1517 // Enable Pointer Capture.
1518 if (haveWindowWithPointerCapture &&
1519 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001520 // This can happen if pointer capture is disabled and re-enabled before we notify the
1521 // app of the state change, so there is no need to notify the app.
1522 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1523 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001524 }
1525 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001526 // This can happen if a window requests capture and immediately releases capture.
1527 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001528 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001529 return;
1530 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001531 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1532 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1533 return;
1534 }
1535
Vishnu Nairc519ff72021-01-21 08:23:08 -08001536 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001537 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1538 mWindowTokenWithPointerCapture = token;
1539 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001540 // Disable Pointer Capture.
1541 // We do not check if the sequence number matches for requests to disable Pointer Capture
1542 // for two reasons:
1543 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1544 // to disable capture with the same sequence number: one generated by
1545 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1546 // Capture being disabled in InputReader.
1547 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1548 // actual Pointer Capture state that affects events being generated by input devices is
1549 // in InputReader.
1550 if (!haveWindowWithPointerCapture) {
1551 // Pointer capture was already forcefully disabled because of focus change.
1552 dropReason = DropReason::NOT_DROPPED;
1553 return;
1554 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001555 token = mWindowTokenWithPointerCapture;
1556 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001557 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001558 setPointerCaptureLocked(false);
1559 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001560 }
1561
1562 auto channel = getInputChannelLocked(token);
1563 if (channel == nullptr) {
1564 // Window has gone away, clean up Pointer Capture state.
1565 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001566 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001567 setPointerCaptureLocked(false);
1568 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001569 return;
1570 }
1571 InputTarget target;
1572 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001573 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001574 entry->dispatchInProgress = true;
1575 dispatchEventLocked(currentTime, entry, {target});
1576
1577 dropReason = DropReason::NOT_DROPPED;
1578}
1579
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001580void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1581 const std::shared_ptr<TouchModeEntry>& entry) {
1582 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001583 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001584 if (windowHandles.empty()) {
1585 return;
1586 }
1587 const std::vector<InputTarget> inputTargets =
1588 getInputTargetsFromWindowHandlesLocked(windowHandles);
1589 if (inputTargets.empty()) {
1590 return;
1591 }
1592 entry->dispatchInProgress = true;
1593 dispatchEventLocked(currentTime, entry, inputTargets);
1594}
1595
1596std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1597 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1598 std::vector<InputTarget> inputTargets;
1599 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001600 const sp<IBinder>& token = handle->getToken();
1601 if (token == nullptr) {
1602 continue;
1603 }
1604 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1605 if (channel == nullptr) {
1606 continue; // Window has gone away
1607 }
1608 InputTarget target;
1609 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001610 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001611 inputTargets.push_back(target);
1612 }
1613 return inputTargets;
1614}
1615
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001616bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001617 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001619 if (!entry->dispatchInProgress) {
1620 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1621 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1622 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1623 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001624 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 // We have seen two identical key downs in a row which indicates that the device
1626 // driver is automatically generating key repeats itself. We take note of the
1627 // repeat here, but we disable our own next key repeat timer since it is clear that
1628 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001629 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1630 // Make sure we don't get key down from a different device. If a different
1631 // device Id has same key pressed down, the new device Id will replace the
1632 // current one to hold the key repeat with repeat count reset.
1633 // In the future when got a KEY_UP on the device id, drop it and do not
1634 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1636 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001637 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 } else {
1639 // Not a repeat. Save key down state in case we do see a repeat later.
1640 resetKeyRepeatLocked();
1641 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1642 }
1643 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001644 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1645 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001646 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001647 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001648 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1649 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001650 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 resetKeyRepeatLocked();
1652 }
1653
1654 if (entry->repeatCount == 1) {
1655 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1656 } else {
1657 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1658 }
1659
1660 entry->dispatchInProgress = true;
1661
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 }
1664
1665 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001666 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 if (currentTime < entry->interceptKeyWakeupTime) {
1668 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1669 *nextWakeupTime = entry->interceptKeyWakeupTime;
1670 }
1671 return false; // wait until next wakeup
1672 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001673 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 entry->interceptKeyWakeupTime = 0;
1675 }
1676
1677 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001678 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001680 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001681 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001682
1683 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1684 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1685 };
1686 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001687 // Poke user activity for keys not passed to user
1688 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 return false; // wait for the command to run
1690 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001691 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001693 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001694 if (*dropReason == DropReason::NOT_DROPPED) {
1695 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 }
1697 }
1698
1699 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001700 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001701 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001702 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1703 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001704 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001705 // Poke user activity for undispatched keys
1706 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 return true;
1708 }
1709
1710 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001711 InputEventInjectionResult injectionResult;
1712 sp<WindowInfoHandle> focusedWindow =
1713 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1714 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 return false;
1717 }
1718
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001719 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001720 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 return true;
1722 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001723 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1724
1725 std::vector<InputTarget> inputTargets;
1726 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001727 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001728 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001730 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001731 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732
1733 // Dispatch the key.
1734 dispatchEventLocked(currentTime, entry, inputTargets);
1735 return true;
1736}
1737
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001738void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001739 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1740 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1741 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1742 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1743 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1744 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1745 entry.metaState, entry.repeatCount, entry.downTime);
1746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747}
1748
Prabir Pradhancef936d2021-07-21 16:17:52 +00001749void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1750 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001751 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001752 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1753 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1754 "source=0x%x, sensorType=%s",
1755 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001756 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001757 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001758 auto command = [this, entry]() REQUIRES(mLock) {
1759 scoped_unlock unlock(mLock);
1760
1761 if (entry->accuracyChanged) {
1762 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1763 }
1764 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1765 entry->hwTimestamp, entry->values);
1766 };
1767 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001768}
1769
1770bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1772 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001773 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001774 }
Chris Yef59a2f42020-10-16 12:55:26 -07001775 { // acquire lock
1776 std::scoped_lock _l(mLock);
1777
1778 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1779 std::shared_ptr<EventEntry> entry = *it;
1780 if (entry->type == EventEntry::Type::SENSOR) {
1781 it = mInboundQueue.erase(it);
1782 releaseInboundEventLocked(entry);
1783 }
1784 }
1785 }
1786 return true;
1787}
1788
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001789bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001790 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001791 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001793 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 entry->dispatchInProgress = true;
1795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
1798
1799 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001800 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001801 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001802 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1803 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 return true;
1805 }
1806
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001807 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
1809 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001810 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811
1812 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 if (isPointerEvent) {
1815 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001816
1817 if (mDragState &&
1818 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1819 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1820 pilferPointersLocked(mDragState->dragWindow->getToken());
1821 }
1822
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001823 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001824 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001825 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001826 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1827 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 } else {
1829 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001830 sp<WindowInfoHandle> focusedWindow =
1831 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1832 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1833 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1834 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001835 InputTarget::Flags::FOREGROUND |
1836 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001837 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 return false;
1842 }
1843
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001844 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001845 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001846 return true;
1847 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001849 CancelationOptions::Mode mode(
1850 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1851 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001852 CancelationOptions options(mode, "input event injection failed");
1853 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 return true;
1855 }
1856
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001857 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001858 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
1860 // Dispatch the motion.
1861 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001862 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 synthesizeCancelationEventsForAllConnectionsLocked(options);
1865 }
1866 dispatchEventLocked(currentTime, entry, inputTargets);
1867 return true;
1868}
1869
chaviw98318de2021-05-19 16:45:23 -05001870void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001871 bool isExiting, const int32_t rawX,
1872 const int32_t rawY) {
1873 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001874 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001875 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1876 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001877
1878 enqueueInboundEventLocked(std::move(dragEntry));
1879}
1880
1881void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1882 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1883 if (channel == nullptr) {
1884 return; // Window has gone away
1885 }
1886 InputTarget target;
1887 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001888 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001889 entry->dispatchInProgress = true;
1890 dispatchEventLocked(currentTime, entry, {target});
1891}
1892
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001893void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001894 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001895 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001896 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001897 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001898 "metaState=0x%x, buttonState=0x%x,"
1899 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001900 prefix, entry.eventTime, entry.deviceId,
1901 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1902 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1903 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1904 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001906 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001907 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001908 "x=%f, y=%f, pressure=%f, size=%f, "
1909 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1910 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001911 i, entry.pointerProperties[i].id,
1912 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001913 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1914 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1915 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1916 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1917 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1918 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1919 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1920 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1921 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924}
1925
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001926void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1927 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001929 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001930 if (DEBUG_DISPATCH_CYCLE) {
1931 ALOGD("dispatchEventToCurrentInputTargets");
1932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001934 updateInteractionTokensLocked(*eventEntry, inputTargets);
1935
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1937
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001938 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001940 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001941 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001942 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001943 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001944 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001946 if (DEBUG_FOCUS) {
1947 ALOGD("Dropping event delivery to target with channel '%s' because it "
1948 "is no longer registered with the input dispatcher.",
1949 inputTarget.inputChannel->getName().c_str());
1950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 }
1952 }
1953}
1954
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001955void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1957 // If the policy decides to close the app, we will get a channel removal event via
1958 // unregisterInputChannel, and will clean up the connection that way. We are already not
1959 // sending new pointers to the connection when it blocked, but focused events will continue to
1960 // pile up.
1961 ALOGW("Canceling events for %s because it is unresponsive",
1962 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001963 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001964 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001965 "application not responding");
1966 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 }
1968}
1969
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001971 if (DEBUG_FOCUS) {
1972 ALOGD("Resetting ANR timeouts.");
1973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974
1975 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001976 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001977 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978}
1979
Tiger Huang721e26f2018-07-24 22:26:19 +08001980/**
1981 * Get the display id that the given event should go to. If this event specifies a valid display id,
1982 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1983 * Focused display is the display that the user most recently interacted with.
1984 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001985int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001986 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001988 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1990 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001991 break;
1992 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001993 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001994 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1995 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001996 break;
1997 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001998 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001999 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002000 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002001 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002002 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002003 case EventEntry::Type::SENSOR:
2004 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002005 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002006 return ADISPLAY_ID_NONE;
2007 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002008 }
2009 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2010}
2011
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002012bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2013 const char* focusedWindowName) {
2014 if (mAnrTracker.empty()) {
2015 // already processed all events that we waited for
2016 mKeyIsWaitingForEventsTimeout = std::nullopt;
2017 return false;
2018 }
2019
2020 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2021 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002022 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002023 mKeyIsWaitingForEventsTimeout = currentTime +
2024 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2025 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 return true;
2027 }
2028
2029 // We still have pending events, and already started the timer
2030 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2031 return true; // Still waiting
2032 }
2033
2034 // Waited too long, and some connection still hasn't processed all motions
2035 // Just send the key to the focused window
2036 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2037 focusedWindowName);
2038 mKeyIsWaitingForEventsTimeout = std::nullopt;
2039 return false;
2040}
2041
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002042sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2043 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2044 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002045 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002046 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047
Tiger Huang721e26f2018-07-24 22:26:19 +08002048 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002049 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002050 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002051 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2052
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 // If there is no currently focused window and no focused application
2054 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002055 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2056 ALOGI("Dropping %s event because there is no focused window or focused application in "
2057 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002058 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002059 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061
Vishnu Nair062a8672021-09-03 16:07:44 -07002062 // Drop key events if requested by input feature
2063 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002064 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002065 }
2066
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2068 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2069 // start interacting with another application via touch (app switch). This code can be removed
2070 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2071 // an app is expected to have a focused window.
2072 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2073 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2074 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002075 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2076 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2077 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002079 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002080 ALOGW("Waiting because no window has focus but %s may eventually add a "
2081 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002082 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002083 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002084 outInjectionResult = InputEventInjectionResult::PENDING;
2085 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2087 // Already raised ANR. Drop the event
2088 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002089 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002090 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 } else {
2092 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002093 outInjectionResult = InputEventInjectionResult::PENDING;
2094 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095 }
2096 }
2097
2098 // we have a valid, non-null focused window
2099 resetNoFocusedWindowTimeoutLocked();
2100
Prabir Pradhan5735a322022-04-11 17:23:34 +00002101 // Verify targeted injection.
2102 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2103 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002104 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2105 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
2107
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002108 if (focusedWindowHandle->getInfo()->inputConfig.test(
2109 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002111 outInjectionResult = InputEventInjectionResult::PENDING;
2112 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 }
2114
2115 // If the event is a key event, then we must wait for all previous events to
2116 // complete before delivering it because previous events may have the
2117 // side-effect of transferring focus to a different window and we want to
2118 // ensure that the following keys are sent to the new window.
2119 //
2120 // Suppose the user touches a button in a window then immediately presses "A".
2121 // If the button causes a pop-up window to appear then we want to ensure that
2122 // the "A" key is delivered to the new pop-up window. This is because users
2123 // often anticipate pending UI changes when typing on a keyboard.
2124 // To obtain this behavior, we must serialize key events with respect to all
2125 // prior input events.
2126 if (entry.type == EventEntry::Type::KEY) {
2127 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2128 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002129 outInjectionResult = InputEventInjectionResult::PENDING;
2130 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002134 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2135 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136}
2137
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002138/**
2139 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2140 * that are currently unresponsive.
2141 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002142std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2143 const std::vector<Monitor>& monitors) const {
2144 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002145 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002146 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002147 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002148 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002149 if (connection == nullptr) {
2150 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002151 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002152 return false;
2153 }
2154 if (!connection->responsive) {
2155 ALOGW("Unresponsive monitor %s will not get the new gesture",
2156 connection->inputChannel->getName().c_str());
2157 return false;
2158 }
2159 return true;
2160 });
2161 return responsiveMonitors;
2162}
2163
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002164/**
2165 * In general, touch should be always split between windows. Some exceptions:
2166 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2167 * from the same device, *and* the window that's receiving the current pointer does not support
2168 * split touch.
2169 * 2. Don't split mouse events
2170 */
2171bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2172 const MotionEntry& entry) const {
2173 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2174 // We should never split mouse events
2175 return false;
2176 }
2177 for (const TouchedWindow& touchedWindow : touchState.windows) {
2178 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2179 // Spy windows should not affect whether or not touch is split.
2180 continue;
2181 }
2182 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2183 continue;
2184 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002185 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2186 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2187 // Wallpaper window should not affect whether or not touch is split
2188 continue;
2189 }
2190
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002191 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2192 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002193 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002194 return false;
2195 }
2196 }
2197 return true;
2198}
2199
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002200std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002201 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2202 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002203 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002205 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 // For security reasons, we defer updating the touch state until we are sure that
2207 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002208 const int32_t displayId = entry.displayId;
2209 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002210 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211
2212 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002213 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002215 // Copy current touch state into tempTouchState.
2216 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2217 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002218 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002219 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002220 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2221 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002222 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002223 }
2224
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002225 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002226 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002227 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002228
2229 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2230 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2231 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002232 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2233 // touchable windows.
2234 const bool wasDown = oldState != nullptr && oldState->isDown();
2235 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2236 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2237 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002238 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002239
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002240 // If pointers are already down, let's finish the current gesture and ignore the new events
2241 // from another device. However, if the new event is a down event, let's cancel the current
2242 // touch and let the new one take over.
2243 if (switchedDevice && wasDown && !isDown) {
2244 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2245 << " is already down in display " << displayId << ": " << entry.getDescription();
2246 // TODO(b/211379801): test multiple simultaneous input streams.
2247 outInjectionResult = InputEventInjectionResult::FAILED;
2248 return {}; // wrong device
2249 }
2250
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002252 // If a new gesture is starting, clear the touch state completely.
2253 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 tempTouchState.deviceId = entry.deviceId;
2255 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002257 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002258 ALOGI("Dropping move event because a pointer for a different device is already active "
2259 "in display %" PRId32,
2260 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002261 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002263 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 }
2265
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002266 if (isHoverAction) {
2267 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2268 // all of the existing hovering pointers and recompute.
2269 tempTouchState.clearHoveringPointers();
2270 }
2271
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2273 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002274 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002275 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002276 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2277 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002278 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002279 auto [newTouchedWindowHandle, outsideTargets] =
2280 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002281
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002282 if (isDown) {
2283 targets += outsideTargets;
2284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002286 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002287 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002289 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002290 }
2291
Prabir Pradhan5735a322022-04-11 17:23:34 +00002292 // Verify targeted injection.
2293 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2294 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002295 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002296 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002297 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002298 }
2299
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002300 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002301 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002302 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2303 // New window supports splitting, but we should never split mouse events.
2304 isSplit = !isFromMouse;
2305 } else if (isSplit) {
2306 // New window does not support splitting but we have already split events.
2307 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002308 newTouchedWindowHandle = nullptr;
2309 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002310 } else {
2311 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002312 // be delivered to a new window which supports split touch. Pointers from a mouse device
2313 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002314 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002315 }
2316
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002317 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002318 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002319 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002320 // Process the foreground window first so that it is the first to receive the event.
2321 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 }
2323
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002324 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002325 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2326 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002327 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002328 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002329 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002330 }
2331
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002332 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002333 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002334 continue;
2335 }
2336
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002337 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2338 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002339 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002340 // The "windowHandle" is the target of this hovering pointer.
2341 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002342 }
2343
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002344 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002345 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002346
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002347 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2348 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002349 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002350 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351
2352 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002353 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002354 }
2355 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002356 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002357 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002358 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002359 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002360
2361 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002362 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002363 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002364 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002365 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002367 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2368 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2369
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002370 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2371 // still add a window to the touch state. We should avoid doing that, but some of the
2372 // later checks ("at least one foreground window") rely on this in order to dispatch
2373 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002374 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002375 isDownOrPointerDown
2376 ? std::make_optional(entry.eventTime)
2377 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002378
2379 // If this is the pointer going down and the touched window has a wallpaper
2380 // then also add the touched wallpaper windows so they are locked in for the duration
2381 // of the touch gesture.
2382 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2383 // engine only supports touch events. We would need to add a mechanism similar
2384 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002385 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002386 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2387 windowHandle->getInfo()->inputConfig.test(
2388 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2389 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2390 if (wallpaper != nullptr) {
2391 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2392 InputTarget::Flags::WINDOW_IS_OBSCURED |
2393 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2394 InputTarget::Flags::DISPATCH_AS_IS;
2395 if (isSplit) {
2396 wallpaperFlags |= InputTarget::Flags::SPLIT;
2397 }
2398 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2399 entry.eventTime);
2400 }
2401 }
2402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002404
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002405 // If a window is already pilfering some pointers, give it this new pointer as well and
2406 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2407 // which is a specific behaviour that we want.
2408 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2409 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002410 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002411 touchedWindow.pilferedPointerIds.count() > 0) {
2412 // This window is already pilfering some pointers, and this new pointer is also
2413 // going to it. Therefore, take over this pointer and don't give it to anyone
2414 // else.
2415 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002416 }
2417 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002418
2419 // Restrict all pilfered pointers to the pilfering windows.
2420 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 } else {
2422 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2423
2424 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002425 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002426 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2427 "dropped the pointer down event in display "
2428 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002429 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002430 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432
arthurhung6d4bed92021-03-17 11:59:33 +08002433 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002434
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002436 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002437 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002438 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002439 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002440 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002441 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002442 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002443 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002444
Prabir Pradhan5735a322022-04-11 17:23:34 +00002445 // Verify targeted injection.
2446 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2447 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002448 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002449 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002450 }
2451
Vishnu Nair062a8672021-09-03 16:07:44 -07002452 // Drop touch events if requested by input feature
2453 if (newTouchedWindowHandle != nullptr &&
2454 shouldDropInput(entry, newTouchedWindowHandle)) {
2455 newTouchedWindowHandle = nullptr;
2456 }
2457
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002458 if (!haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
2459 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2460 oldTouchedWindowHandle->getName().c_str(),
2461 newTouchedWindowHandle->getName().c_str(), displayId);
2462
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002464 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002465 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002466 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002467
2468 const TouchedWindow& touchedWindow =
2469 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2470 addWindowTargetLocked(oldTouchedWindowHandle,
2471 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2472 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473
2474 // Make a slippery entrance into the new window.
2475 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002476 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 }
2478
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002479 ftl::Flags<InputTarget::Flags> targetFlags =
2480 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002481 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002482 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002485 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 }
2487 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002488 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002489 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002490 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
2492
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002493 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2494 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002495
2496 // Check if the wallpaper window should deliver the corresponding event.
2497 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002498 tempTouchState, pointerId, targets);
2499 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
2501 }
Arthur Hung96483742022-11-15 03:30:48 +00002502
2503 // Update the pointerIds for non-splittable when it received pointer down.
2504 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2505 // If no split, we suppose all touched windows should receive pointer down.
2506 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2507 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2508 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2509 // Ignore drag window for it should just track one pointer.
2510 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2511 continue;
2512 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002513 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002514 }
2515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 }
2517
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002518 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002519 {
2520 std::vector<TouchedWindow> hoveringWindows =
2521 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2522 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2523 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2524 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2525 targets);
2526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002528 // Ensure that we have at least one foreground window or at least one window that cannot be a
2529 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2530 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2531 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002532 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2533 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002534 return !canReceiveForegroundTouches(
2535 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002536 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002537 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002538 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2539 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002540 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002541 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
2543
Prabir Pradhan5735a322022-04-11 17:23:34 +00002544 // Ensure that all touched windows are valid for injection.
2545 if (entry.injectionState != nullptr) {
2546 std::string errs;
2547 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002548 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002549 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2550 // dispatched to any uid, since the coords will be zeroed out later.
2551 continue;
2552 }
2553 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2554 if (err) errs += "\n - " + *err;
2555 }
2556 if (!errs.empty()) {
2557 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2558 "%d:%s",
2559 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002560 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002561 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002562 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002563 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002564
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002565 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2566 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002568 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002569 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002570 if (foregroundWindowHandle) {
2571 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002572 for (InputTarget& target : targets) {
2573 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2574 sp<WindowInfoHandle> targetWindow =
2575 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2576 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2577 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 }
2580 }
2581 }
2582 }
2583
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002584 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002585 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002586 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002587 // Windows with hovering pointers are getting persisted inside TouchState.
2588 // Do not send this event to those windows.
2589 continue;
2590 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002591 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2592 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2593 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002594 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002595
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002596 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002597 // Drop the outside or hover touch windows since we will not care about them
2598 // in the next iteration.
2599 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002602 if (switchedDevice) {
2603 if (DEBUG_FOCUS) {
2604 ALOGD("Conflicting pointer actions: Switched to a different device.");
2605 }
2606 *outConflictingPointerActions = true;
2607 }
2608
2609 if (isHoverAction) {
2610 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002611 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002612 ALOGD_IF(DEBUG_FOCUS,
2613 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002614 *outConflictingPointerActions = true;
2615 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002616 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2617 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2618 tempTouchState.deviceId = entry.deviceId;
2619 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002620 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002621 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2622 // Pointer went up.
2623 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002624 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002625 // All pointers up or canceled.
2626 tempTouchState.reset();
2627 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2628 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002629 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2630 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002631 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002632 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002633 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2634 // One pointer went up.
2635 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2636 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002638 for (size_t i = 0; i < tempTouchState.windows.size();) {
2639 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002640 touchedWindow.pointerIds.reset(pointerId);
2641 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002642 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2643 continue;
2644 }
2645 i += 1;
2646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 }
2648
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002649 // Save changes unless the action was scroll in which case the temporary touch
2650 // state was only valid for this one action.
2651 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002652 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002653 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002654 mTouchStatesByDisplay[displayId] = tempTouchState;
2655 } else {
2656 mTouchStatesByDisplay.erase(displayId);
2657 }
2658 }
2659
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002660 if (tempTouchState.windows.empty()) {
2661 mTouchStatesByDisplay.erase(displayId);
2662 }
2663
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002664 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665}
2666
arthurhung6d4bed92021-03-17 11:59:33 +08002667void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002668 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2669 // have an explicit reason to support it.
2670 constexpr bool isStylus = false;
2671
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002672 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002673 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002674 if (dropWindow) {
2675 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002676 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002677 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002678 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002679 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002680 }
2681 mDragState.reset();
2682}
2683
2684void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002685 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002686 return;
2687 }
2688
arthurhung6d4bed92021-03-17 11:59:33 +08002689 if (!mDragState->isStartDrag) {
2690 mDragState->isStartDrag = true;
2691 mDragState->isStylusButtonDownAtStart =
2692 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2693 }
2694
Arthur Hung54745652022-04-20 07:17:41 +00002695 // Find the pointer index by id.
2696 int32_t pointerIndex = 0;
2697 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2698 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2699 if (pointerProperties.id == mDragState->pointerId) {
2700 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002701 }
Arthur Hung54745652022-04-20 07:17:41 +00002702 }
arthurhung6d4bed92021-03-17 11:59:33 +08002703
Arthur Hung54745652022-04-20 07:17:41 +00002704 if (uint32_t(pointerIndex) == entry.pointerCount) {
2705 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002706 }
2707
2708 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2709 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2710 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2711
2712 switch (maskedAction) {
2713 case AMOTION_EVENT_ACTION_MOVE: {
2714 // Handle the special case : stylus button no longer pressed.
2715 bool isStylusButtonDown =
2716 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2717 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2718 finishDragAndDrop(entry.displayId, x, y);
2719 return;
2720 }
2721
2722 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2723 // until we have an explicit reason to support it.
2724 constexpr bool isStylus = false;
2725
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002726 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002727 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002728 // enqueue drag exit if needed.
2729 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2730 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2731 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002732 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002733 y);
2734 }
2735 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2736 }
2737 // enqueue drag location if needed.
2738 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002739 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002740 }
2741 break;
2742 }
2743
2744 case AMOTION_EVENT_ACTION_POINTER_UP:
2745 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2746 break;
2747 }
2748 // The drag pointer is up.
2749 [[fallthrough]];
2750 case AMOTION_EVENT_ACTION_UP:
2751 finishDragAndDrop(entry.displayId, x, y);
2752 break;
2753 case AMOTION_EVENT_ACTION_CANCEL: {
2754 ALOGD("Receiving cancel when drag and drop.");
2755 sendDropWindowCommandLocked(nullptr, 0, 0);
2756 mDragState.reset();
2757 break;
2758 }
arthurhungb89ccb02020-12-30 16:19:01 +08002759 }
2760}
2761
chaviw98318de2021-05-19 16:45:23 -05002762void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002763 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002764 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002765 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002766 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002767 std::vector<InputTarget>::iterator it =
2768 std::find_if(inputTargets.begin(), inputTargets.end(),
2769 [&windowHandle](const InputTarget& inputTarget) {
2770 return inputTarget.inputChannel->getConnectionToken() ==
2771 windowHandle->getToken();
2772 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002773
chaviw98318de2021-05-19 16:45:23 -05002774 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002775
2776 if (it == inputTargets.end()) {
2777 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002778 std::shared_ptr<InputChannel> inputChannel =
2779 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002780 if (inputChannel == nullptr) {
2781 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2782 return;
2783 }
2784 inputTarget.inputChannel = inputChannel;
2785 inputTarget.flags = targetFlags;
2786 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002787 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002788 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2789 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002790 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002791 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002792 // DisplayInfo not found for this window on display windowInfo->displayId.
2793 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002794 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002795 inputTargets.push_back(inputTarget);
2796 it = inputTargets.end() - 1;
2797 }
2798
2799 ALOG_ASSERT(it->flags == targetFlags);
2800 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2801
chaviw1ff3d1e2020-07-01 15:53:47 -07002802 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803}
2804
Michael Wright3dd60e22019-03-27 22:06:44 +00002805void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002806 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002807 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2808 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002809
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002810 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2811 InputTarget target;
2812 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002813 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002814 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2815 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002816 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2817 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002818 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002819 target.setDefaultPointerTransform(target.displayTransform);
2820 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 }
2822}
2823
Robert Carrc9bf1d32020-04-13 17:21:08 -07002824/**
2825 * Indicate whether one window handle should be considered as obscuring
2826 * another window handle. We only check a few preconditions. Actually
2827 * checking the bounds is left to the caller.
2828 */
chaviw98318de2021-05-19 16:45:23 -05002829static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2830 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002831 // Compare by token so cloned layers aren't counted
2832 if (haveSameToken(windowHandle, otherHandle)) {
2833 return false;
2834 }
2835 auto info = windowHandle->getInfo();
2836 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002837 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002838 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002839 } else if (otherInfo->alpha == 0 &&
2840 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002841 // Those act as if they were invisible, so we don't need to flag them.
2842 // We do want to potentially flag touchable windows even if they have 0
2843 // opacity, since they can consume touches and alter the effects of the
2844 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002845 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002846 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2847 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002848 } else if (info->ownerUid == otherInfo->ownerUid) {
2849 // If ownerUid is the same we don't generate occlusion events as there
2850 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002851 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002852 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002853 return false;
2854 } else if (otherInfo->displayId != info->displayId) {
2855 return false;
2856 }
2857 return true;
2858}
2859
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002860/**
2861 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2862 * untrusted, one should check:
2863 *
2864 * 1. If result.hasBlockingOcclusion is true.
2865 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2866 * BLOCK_UNTRUSTED.
2867 *
2868 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2869 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2870 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2871 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2872 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2873 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2874 *
2875 * If neither of those is true, then it means the touch can be allowed.
2876 */
2877InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002878 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2879 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002880 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002881 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002882 TouchOcclusionInfo info;
2883 info.hasBlockingOcclusion = false;
2884 info.obscuringOpacity = 0;
2885 info.obscuringUid = -1;
2886 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002887 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002888 if (windowHandle == otherHandle) {
2889 break; // All future windows are below us. Exit early.
2890 }
chaviw98318de2021-05-19 16:45:23 -05002891 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002892 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2893 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002894 if (DEBUG_TOUCH_OCCLUSION) {
2895 info.debugInfo.push_back(
2896 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2897 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002898 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2899 // we perform the checks below to see if the touch can be propagated or not based on the
2900 // window's touch occlusion mode
2901 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2902 info.hasBlockingOcclusion = true;
2903 info.obscuringUid = otherInfo->ownerUid;
2904 info.obscuringPackage = otherInfo->packageName;
2905 break;
2906 }
2907 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2908 uint32_t uid = otherInfo->ownerUid;
2909 float opacity =
2910 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2911 // Given windows A and B:
2912 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2913 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2914 opacityByUid[uid] = opacity;
2915 if (opacity > info.obscuringOpacity) {
2916 info.obscuringOpacity = opacity;
2917 info.obscuringUid = uid;
2918 info.obscuringPackage = otherInfo->packageName;
2919 }
2920 }
2921 }
2922 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002923 if (DEBUG_TOUCH_OCCLUSION) {
2924 info.debugInfo.push_back(
2925 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2926 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002927 return info;
2928}
2929
chaviw98318de2021-05-19 16:45:23 -05002930std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002931 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002932 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2933 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2934 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2935 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002936 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2937 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2938 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2939 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2940 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002941 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002942 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002943}
2944
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002945bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2946 if (occlusionInfo.hasBlockingOcclusion) {
2947 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2948 occlusionInfo.obscuringUid);
2949 return false;
2950 }
2951 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2952 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2953 "%.2f, maximum allowed = %.2f)",
2954 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2955 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2956 return false;
2957 }
2958 return true;
2959}
2960
chaviw98318de2021-05-19 16:45:23 -05002961bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002964 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2965 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002966 if (windowHandle == otherHandle) {
2967 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 }
chaviw98318de2021-05-19 16:45:23 -05002969 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002970 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002971 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 return true;
2973 }
2974 }
2975 return false;
2976}
2977
chaviw98318de2021-05-19 16:45:23 -05002978bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002979 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002980 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2981 const WindowInfo* windowInfo = windowHandle->getInfo();
2982 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002983 if (windowHandle == otherHandle) {
2984 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002985 }
chaviw98318de2021-05-19 16:45:23 -05002986 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002987 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002988 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002989 return true;
2990 }
2991 }
2992 return false;
2993}
2994
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002995std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002996 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002997 if (applicationHandle != nullptr) {
2998 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002999 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 } else {
3001 return applicationHandle->getName();
3002 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003003 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003004 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003006 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 }
3008}
3009
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003010void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003011 if (!isUserActivityEvent(eventEntry)) {
3012 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003013 return;
3014 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003015 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003016 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003017 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003018 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003019 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003020 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003021 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 }
3023 }
3024
3025 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003026 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003027 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003028 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3029 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 return;
3031 }
Josep del Riob3981622023-04-18 15:49:45 +00003032 if (windowDisablingUserActivityInfo != nullptr) {
3033 if (DEBUG_DISPATCH_CYCLE) {
3034 ALOGD("Not poking user activity: disabled by window '%s'.",
3035 windowDisablingUserActivityInfo->name.c_str());
3036 }
3037 return;
3038 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 eventType = USER_ACTIVITY_EVENT_TOUCH;
3041 }
3042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003044 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003045 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3046 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 return;
3048 }
Josep del Riob3981622023-04-18 15:49:45 +00003049 // If the key code is unknown, we don't consider it user activity
3050 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3051 return;
3052 }
3053 // Don't inhibit events that were intercepted or are not passed to
3054 // the apps, like system shortcuts
3055 if (windowDisablingUserActivityInfo != nullptr &&
3056 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3057 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3058 if (DEBUG_DISPATCH_CYCLE) {
3059 ALOGD("Not poking user activity: disabled by window '%s'.",
3060 windowDisablingUserActivityInfo->name.c_str());
3061 }
3062 return;
3063 }
3064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 eventType = USER_ACTIVITY_EVENT_BUTTON;
3066 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003068 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003069 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003070 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003071 break;
3072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 }
3074
Prabir Pradhancef936d2021-07-21 16:17:52 +00003075 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3076 REQUIRES(mLock) {
3077 scoped_unlock unlock(mLock);
3078 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3079 };
3080 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081}
3082
3083void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003084 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003085 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003086 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003087 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003089 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003090 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003091 ATRACE_NAME(message.c_str());
3092 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003093 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003094 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003095 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003096 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003097 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003098 inputTarget.getPointerInfoString().c_str());
3099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
3101 // Skip this event if the connection status is not normal.
3102 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003103 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003104 if (DEBUG_DISPATCH_CYCLE) {
3105 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003106 connection->getInputChannelName().c_str(),
3107 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 return;
3110 }
3111
3112 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003113 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003114 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003115 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003116 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003119 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003120 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3121 logDispatchStateLocked();
3122 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3123 "target on connection "
3124 << connection->getInputChannelName() << " for "
3125 << originalMotionEntry.getDescription();
3126 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003127 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003128 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3129 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 if (!splitMotionEntry) {
3131 return; // split event was dropped
3132 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003133 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3134 std::string reason = std::string("reason=pointer cancel on split window");
3135 android_log_event_list(LOGTAG_INPUT_CANCEL)
3136 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3137 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003138 if (DEBUG_FOCUS) {
3139 ALOGD("channel '%s' ~ Split motion event.",
3140 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003141 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003142 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003143 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3144 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 return;
3146 }
3147 }
3148
3149 // Not splitting. Enqueue dispatch entries for the event as is.
3150 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3151}
3152
3153void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003154 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003155 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003156 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003157 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003159 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003160 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003161 ATRACE_NAME(message.c_str());
3162 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003163 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3164 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003165
hongzuo liu95785e22022-09-06 02:51:35 +00003166 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167
3168 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003169 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003170 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003171 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003172 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003173 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003174 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003175 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003176 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003177 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003178 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003179 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003180 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181
3182 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003183 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 startDispatchCycleLocked(currentTime, connection);
3185 }
3186}
3187
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003188void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003189 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003190 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003192 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3194 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003196 ATRACE_NAME(message.c_str());
3197 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003198 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3199 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 return;
3201 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003202
3203 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3204 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
3206 // This is a new event.
3207 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003208 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003209 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003211 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3212 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003213 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003215 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003216 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003217 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003218 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003219 dispatchEntry->resolvedAction = keyEntry.action;
3220 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3223 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003224 if (DEBUG_DISPATCH_CYCLE) {
3225 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3226 "event",
3227 connection->getInputChannelName().c_str());
3228 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 return; // skip the inconsistent event
3230 }
3231 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003234 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003235 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3237 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3238 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3239 static_cast<int32_t>(IdGenerator::Source::OTHER);
3240 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003241 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003243 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003245 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003247 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003249 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3251 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003252 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003253 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 }
3255 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003256 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3257 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003258 if (DEBUG_DISPATCH_CYCLE) {
3259 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3260 "enter event",
3261 connection->getInputChannelName().c_str());
3262 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003263 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3264 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003268 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003269 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3270 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3271 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3274 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3280 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003281 if (DEBUG_DISPATCH_CYCLE) {
3282 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3283 "event",
3284 connection->getInputChannelName().c_str());
3285 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003286 return; // skip the inconsistent event
3287 }
3288
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003289 dispatchEntry->resolvedEventId =
3290 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3291 ? mIdGenerator.nextId()
3292 : motionEntry.id;
3293 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3294 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3295 ") to MotionEvent(id=0x%" PRIx32 ").",
3296 motionEntry.id, dispatchEntry->resolvedEventId);
3297 ATRACE_NAME(message.c_str());
3298 }
3299
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003300 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3301 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3302 // Skip reporting pointer down outside focus to the policy.
3303 break;
3304 }
3305
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003306 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003307 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308
3309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003311 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003312 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003313 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3314 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003315 break;
3316 }
Chris Yef59a2f42020-10-16 12:55:26 -07003317 case EventEntry::Type::SENSOR: {
3318 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3319 break;
3320 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003321 case EventEntry::Type::CONFIGURATION_CHANGED:
3322 case EventEntry::Type::DEVICE_RESET: {
3323 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003324 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003325 break;
3326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 }
3328
3329 // Remember that we are waiting for this dispatch to complete.
3330 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003331 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
3333
3334 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003335 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003336 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003337}
3338
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003339/**
3340 * This function is purely for debugging. It helps us understand where the user interaction
3341 * was taking place. For example, if user is touching launcher, we will see a log that user
3342 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3343 * We will see both launcher and wallpaper in that list.
3344 * Once the interaction with a particular set of connections starts, no new logs will be printed
3345 * until the set of interacted connections changes.
3346 *
3347 * The following items are skipped, to reduce the logspam:
3348 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3349 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3350 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3351 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3352 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003353 */
3354void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3355 const std::vector<InputTarget>& targets) {
3356 // Skip ACTION_UP events, and all events other than keys and motions
3357 if (entry.type == EventEntry::Type::KEY) {
3358 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3359 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3360 return;
3361 }
3362 } else if (entry.type == EventEntry::Type::MOTION) {
3363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3364 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3365 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3366 return;
3367 }
3368 } else {
3369 return; // Not a key or a motion
3370 }
3371
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003372 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003373 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003374 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003375 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003376 continue; // Skip windows that receive ACTION_OUTSIDE
3377 }
3378
3379 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003380 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003381 if (connection == nullptr) {
3382 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003383 }
3384 newConnectionTokens.insert(std::move(token));
3385 newConnections.emplace_back(connection);
3386 }
3387 if (newConnectionTokens == mInteractionConnectionTokens) {
3388 return; // no change
3389 }
3390 mInteractionConnectionTokens = newConnectionTokens;
3391
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003392 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003393 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003394 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003395 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003396 std::string message = "Interaction with: " + targetList;
3397 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003398 message += "<none>";
3399 }
3400 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3401}
3402
chaviwfd6d3512019-03-25 13:23:49 -07003403void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003404 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003405 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003406 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3407 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003408 return;
3409 }
3410
Vishnu Nairc519ff72021-01-21 08:23:08 -08003411 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003412 if (focusedToken == token) {
3413 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003414 return;
3415 }
3416
Prabir Pradhancef936d2021-07-21 16:17:52 +00003417 auto command = [this, token]() REQUIRES(mLock) {
3418 scoped_unlock unlock(mLock);
3419 mPolicy->onPointerDownOutsideFocus(token);
3420 };
3421 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422}
3423
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003424status_t InputDispatcher::publishMotionEvent(Connection& connection,
3425 DispatchEntry& dispatchEntry) const {
3426 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3427 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3428
3429 PointerCoords scaledCoords[MAX_POINTERS];
3430 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3431
3432 // Set the X and Y offset and X and Y scale depending on the input source.
3433 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003434 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003435 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3436 if (globalScaleFactor != 1.0f) {
3437 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3438 scaledCoords[i] = motionEntry.pointerCoords[i];
3439 // Don't apply window scale here since we don't want scale to affect raw
3440 // coordinates. The scale will be sent back to the client and applied
3441 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003442 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003443 }
3444 usingCoords = scaledCoords;
3445 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003446 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003447 // We don't want the dispatch target to know the coordinates
3448 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3449 scaledCoords[i].clear();
3450 }
3451 usingCoords = scaledCoords;
3452 }
3453
3454 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3455
3456 // Publish the motion event.
3457 return connection.inputPublisher
3458 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3459 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3460 std::move(hmac), dispatchEntry.resolvedAction,
3461 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3462 motionEntry.edgeFlags, motionEntry.metaState,
3463 motionEntry.buttonState, motionEntry.classification,
3464 dispatchEntry.transform, motionEntry.xPrecision,
3465 motionEntry.yPrecision, motionEntry.xCursorPosition,
3466 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3467 motionEntry.downTime, motionEntry.eventTime,
3468 motionEntry.pointerCount, motionEntry.pointerProperties,
3469 usingCoords);
3470}
3471
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003473 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003474 if (ATRACE_ENABLED()) {
3475 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003476 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003477 ATRACE_NAME(message.c_str());
3478 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003479 if (DEBUG_DISPATCH_CYCLE) {
3480 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003483 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003484 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003486 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003487 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488
3489 // Publish the event.
3490 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003491 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3492 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003493 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003494 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3495 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003496 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3497 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3498 << connection->getInputChannelName();
3499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003501 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003502 status = connection->inputPublisher
3503 .publishKeyEvent(dispatchEntry->seq,
3504 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3505 keyEntry.source, keyEntry.displayId,
3506 std::move(hmac), dispatchEntry->resolvedAction,
3507 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3508 keyEntry.scanCode, keyEntry.metaState,
3509 keyEntry.repeatCount, keyEntry.downTime,
3510 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
3513
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003514 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003515 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3516 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3517 << connection->getInputChannelName();
3518 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003519 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 break;
3521 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003522
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003523 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003524 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003525 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003526 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003527 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003528 break;
3529 }
3530
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003531 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3532 const TouchModeEntry& touchModeEntry =
3533 static_cast<const TouchModeEntry&>(eventEntry);
3534 status = connection->inputPublisher
3535 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3536 touchModeEntry.inTouchMode);
3537
3538 break;
3539 }
3540
Prabir Pradhan99987712020-11-10 18:43:05 -08003541 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3542 const auto& captureEntry =
3543 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3544 status = connection->inputPublisher
3545 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003546 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003547 break;
3548 }
3549
arthurhungb89ccb02020-12-30 16:19:01 +08003550 case EventEntry::Type::DRAG: {
3551 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3552 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3553 dragEntry.id, dragEntry.x,
3554 dragEntry.y,
3555 dragEntry.isExiting);
3556 break;
3557 }
3558
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003559 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003560 case EventEntry::Type::DEVICE_RESET:
3561 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003562 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003563 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567
3568 // Check the result.
3569 if (status) {
3570 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003571 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003573 "This is unexpected because the wait queue is empty, so the pipe "
3574 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003575 "event to it, 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 } else {
3580 // Pipe is full and we are waiting for the app to finish process some events
3581 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003582 if (DEBUG_DISPATCH_CYCLE) {
3583 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3584 "waiting for the application to catch up",
3585 connection->getInputChannelName().c_str());
3586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 }
3588 } else {
3589 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003590 "status=%s(%d)",
3591 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3592 status);
Harry Cutts33476232023-01-30 19:57:29 +00003593 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595 return;
3596 }
3597
3598 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003599 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3600 connection->outboundQueue.end(),
3601 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003602 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003603 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003604 if (connection->responsive) {
3605 mAnrTracker.insert(dispatchEntry->timeoutTime,
3606 connection->inputChannel->getConnectionToken());
3607 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003608 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610}
3611
chaviw09c8d2d2020-08-24 15:48:26 -07003612std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3613 size_t size;
3614 switch (event.type) {
3615 case VerifiedInputEvent::Type::KEY: {
3616 size = sizeof(VerifiedKeyEvent);
3617 break;
3618 }
3619 case VerifiedInputEvent::Type::MOTION: {
3620 size = sizeof(VerifiedMotionEvent);
3621 break;
3622 }
3623 }
3624 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3625 return mHmacKeyManager.sign(start, size);
3626}
3627
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003628const std::array<uint8_t, 32> InputDispatcher::getSignature(
3629 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003630 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003631 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003632 // Only sign events up and down events as the purely move events
3633 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003634 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003635 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003636
3637 VerifiedMotionEvent verifiedEvent =
3638 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3639 verifiedEvent.actionMasked = actionMasked;
3640 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3641 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003642}
3643
3644const std::array<uint8_t, 32> InputDispatcher::getSignature(
3645 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3646 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3647 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3648 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003649 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003650}
3651
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003653 const std::shared_ptr<Connection>& connection,
3654 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003655 if (DEBUG_DISPATCH_CYCLE) {
3656 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3657 connection->getInputChannelName().c_str(), seq, toString(handled));
3658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003660 if (connection->status == Connection::Status::BROKEN ||
3661 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 return;
3663 }
3664
3665 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003666 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3667 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3668 };
3669 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670}
3671
3672void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003673 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003674 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003675 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003676 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3677 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679
3680 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003681 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003682 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003683 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003684 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685
3686 // The connection appears to be unrecoverably broken.
3687 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003688 if (connection->status == Connection::Status::NORMAL) {
3689 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690
3691 if (notify) {
3692 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003693 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3694 connection->getInputChannelName().c_str());
3695
3696 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003697 scoped_unlock unlock(mLock);
3698 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3699 };
3700 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702 }
3703}
3704
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003705void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3706 while (!queue.empty()) {
3707 DispatchEntry* dispatchEntry = queue.front();
3708 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003709 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
3711}
3712
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003713void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
3717 delete dispatchEntry;
3718}
3719
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003720int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3721 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003722 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003723 if (connection == nullptr) {
3724 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3725 connectionToken.get(), events);
3726 return 0; // remove the callback
3727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003729 bool notify;
3730 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3731 if (!(events & ALOOPER_EVENT_INPUT)) {
3732 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3733 "events=0x%x",
3734 connection->getInputChannelName().c_str(), events);
3735 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003738 nsecs_t currentTime = now();
3739 bool gotOne = false;
3740 status_t status = OK;
3741 for (;;) {
3742 Result<InputPublisher::ConsumerResponse> result =
3743 connection->inputPublisher.receiveConsumerResponse();
3744 if (!result.ok()) {
3745 status = result.error().code();
3746 break;
3747 }
3748
3749 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3750 const InputPublisher::Finished& finish =
3751 std::get<InputPublisher::Finished>(*result);
3752 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3753 finish.consumeTime);
3754 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003755 if (shouldReportMetricsForConnection(*connection)) {
3756 const InputPublisher::Timeline& timeline =
3757 std::get<InputPublisher::Timeline>(*result);
3758 mLatencyTracker
3759 .trackGraphicsLatency(timeline.inputEventId,
3760 connection->inputChannel->getConnectionToken(),
3761 std::move(timeline.graphicsTimeline));
3762 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003763 }
3764 gotOne = true;
3765 }
3766 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003767 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003768 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 return 1;
3770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 }
3772
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003773 notify = status != DEAD_OBJECT || !connection->monitor;
3774 if (notify) {
3775 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3776 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3777 status);
3778 }
3779 } else {
3780 // Monitor channels are never explicitly unregistered.
3781 // We do it automatically when the remote endpoint is closed so don't warn about them.
3782 const bool stillHaveWindowHandle =
3783 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3784 notify = !connection->monitor && stillHaveWindowHandle;
3785 if (notify) {
3786 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3787 connection->getInputChannelName().c_str(), events);
3788 }
3789 }
3790
3791 // Remove the channel.
3792 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3793 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794}
3795
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003796void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003798 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003799 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
3801}
3802
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003803void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003804 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003805 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003806 for (const Monitor& monitor : monitors) {
3807 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003808 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003809 }
3810}
3811
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003813 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003814 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003815 if (connection == nullptr) {
3816 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003818
3819 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820}
3821
3822void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003823 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003824 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 return;
3826 }
3827
3828 nsecs_t currentTime = now();
3829
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003830 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003831 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003833 if (cancelationEvents.empty()) {
3834 return;
3835 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003836 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3837 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003838 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003839 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003840 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003841 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003842
Arthur Hungb3307ee2021-10-14 10:57:37 +00003843 std::string reason = std::string("reason=").append(options.reason);
3844 android_log_event_list(LOGTAG_INPUT_CANCEL)
3845 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3846
Svet Ganov5d3bc372020-01-26 23:11:07 -08003847 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003848 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003849 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3850 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003851 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003852 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003853 target.globalScaleFactor = windowInfo->globalScaleFactor;
3854 }
3855 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003856 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003857
hongzuo liu95785e22022-09-06 02:51:35 +00003858 const bool wasEmpty = connection->outboundQueue.empty();
3859
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003860 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003861 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003862 switch (cancelationEventEntry->type) {
3863 case EventEntry::Type::KEY: {
3864 logOutboundKeyDetails("cancel - ",
3865 static_cast<const KeyEntry&>(*cancelationEventEntry));
3866 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003868 case EventEntry::Type::MOTION: {
3869 logOutboundMotionDetails("cancel - ",
3870 static_cast<const MotionEntry&>(*cancelationEventEntry));
3871 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003873 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003874 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003875 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3876 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003877 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003878 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003879 break;
3880 }
3881 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003882 case EventEntry::Type::DEVICE_RESET:
3883 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003884 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003885 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003886 break;
3887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 }
3889
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003890 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003891 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003893
hongzuo liu95785e22022-09-06 02:51:35 +00003894 // If the outbound queue was previously empty, start the dispatch cycle going.
3895 if (wasEmpty && !connection->outboundQueue.empty()) {
3896 startDispatchCycleLocked(currentTime, connection);
3897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898}
3899
Svet Ganov5d3bc372020-01-26 23:11:07 -08003900void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003901 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003902 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003903 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003904 return;
3905 }
3906
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003907 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003908 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003909
3910 if (downEvents.empty()) {
3911 return;
3912 }
3913
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003914 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003915 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3916 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003917 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003918
3919 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003920 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003921 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3922 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003923 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003924 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003925 target.globalScaleFactor = windowInfo->globalScaleFactor;
3926 }
3927 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003928 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003929
hongzuo liu95785e22022-09-06 02:51:35 +00003930 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003931 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003932 switch (downEventEntry->type) {
3933 case EventEntry::Type::MOTION: {
3934 logOutboundMotionDetails("down - ",
3935 static_cast<const MotionEntry&>(*downEventEntry));
3936 break;
3937 }
3938
3939 case EventEntry::Type::KEY:
3940 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003941 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003942 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003943 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003944 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003945 case EventEntry::Type::SENSOR:
3946 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003947 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003948 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 break;
3950 }
3951 }
3952
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003953 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003954 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003955 }
3956
hongzuo liu95785e22022-09-06 02:51:35 +00003957 // If the outbound queue was previously empty, start the dispatch cycle going.
3958 if (wasEmpty && !connection->outboundQueue.empty()) {
3959 startDispatchCycleLocked(downTime, connection);
3960 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003961}
3962
Arthur Hungc539dbb2022-12-08 07:45:36 +00003963void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3964 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3965 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003966 std::shared_ptr<Connection> wallpaperConnection =
3967 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00003968 if (wallpaperConnection != nullptr) {
3969 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3970 }
3971 }
3972}
3973
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003974std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003975 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3976 nsecs_t splitDownTime) {
3977 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
3979 uint32_t splitPointerIndexMap[MAX_POINTERS];
3980 PointerProperties splitPointerProperties[MAX_POINTERS];
3981 PointerCoords splitPointerCoords[MAX_POINTERS];
3982
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003983 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 uint32_t splitPointerCount = 0;
3985
3986 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003987 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003989 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003991 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3993 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3994 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003995 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 splitPointerCount += 1;
3997 }
3998 }
3999
4000 if (splitPointerCount != pointerIds.count()) {
4001 // This is bad. We are missing some of the pointers that we expected to deliver.
4002 // Most likely this indicates that we received an ACTION_MOVE events that has
4003 // different pointer ids than we expected based on the previous ACTION_DOWN
4004 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4005 // in this way.
4006 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004007 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004008 "a broken sequence of pointer ids from the input device: %s",
4009 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004010 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 }
4012
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004013 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4016 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4018 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004019 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004021 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 if (pointerIds.count() == 1) {
4023 // The first/last pointer went down/up.
4024 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004026 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4027 ? AMOTION_EVENT_ACTION_CANCEL
4028 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 } else {
4030 // A secondary pointer went down/up.
4031 uint32_t splitPointerIndex = 0;
4032 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4033 splitPointerIndex += 1;
4034 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004035 action = maskedAction |
4036 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 }
4038 } else {
4039 // An unrelated pointer changed.
4040 action = AMOTION_EVENT_ACTION_MOVE;
4041 }
4042 }
4043
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004044 if (action == AMOTION_EVENT_ACTION_DOWN) {
4045 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
4046 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08004047 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4048 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004049 }
4050
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004051 int32_t newId = mIdGenerator.nextId();
4052 if (ATRACE_ENABLED()) {
4053 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4054 ") to MotionEvent(id=0x%" PRIx32 ").",
4055 originalMotionEntry.id, newId);
4056 ATRACE_NAME(message.c_str());
4057 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058 std::unique_ptr<MotionEntry> splitMotionEntry =
4059 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4060 originalMotionEntry.deviceId, originalMotionEntry.source,
4061 originalMotionEntry.displayId,
4062 originalMotionEntry.policyFlags, action,
4063 originalMotionEntry.actionButton,
4064 originalMotionEntry.flags, originalMotionEntry.metaState,
4065 originalMotionEntry.buttonState,
4066 originalMotionEntry.classification,
4067 originalMotionEntry.edgeFlags,
4068 originalMotionEntry.xPrecision,
4069 originalMotionEntry.yPrecision,
4070 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004071 originalMotionEntry.yCursorPosition, splitDownTime,
4072 splitPointerCount, splitPointerProperties,
4073 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004075 if (originalMotionEntry.injectionState) {
4076 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 splitMotionEntry->injectionState->refCount += 1;
4078 }
4079
4080 return splitMotionEntry;
4081}
4082
Prabir Pradhan678438e2023-04-13 19:32:51 +00004083void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004084 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004085 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087
Antonio Kantekf16f2832021-09-28 04:39:20 +00004088 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004090 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004092 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004093 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004094 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 } // release lock
4096
4097 if (needWake) {
4098 mLooper->wake();
4099 }
4100}
4101
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004102/**
4103 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004104 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4105 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4106 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4107 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4108 * potentially handle the back key presses.
4109 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4110 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004111 */
4112void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004114 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4115 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004116 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004117 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004118 }
4119 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004120 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004121 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004122 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004123 keyCode = newKeyCode;
4124 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4125 }
4126 } else if (action == AKEY_EVENT_ACTION_UP) {
4127 // In order to maintain a consistent stream of up and down events, check to see if the key
4128 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4129 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004130 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004131 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004132 auto replacementIt = mReplacedKeys.find(replacement);
4133 if (replacementIt != mReplacedKeys.end()) {
4134 keyCode = replacementIt->second;
4135 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004136 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4137 }
4138 }
4139}
4140
Prabir Pradhan678438e2023-04-13 19:32:51 +00004141void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004142 ALOGD_IF(debugInboundEventDetails(),
4143 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4144 ", deviceId=%d, source=%s, displayId=%" PRId32
4145 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4146 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004147 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4148 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4149 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004150 Result<void> keyCheck = validateKeyEvent(args.action);
4151 if (!keyCheck.ok()) {
4152 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 return;
4154 }
4155
Prabir Pradhan678438e2023-04-13 19:32:51 +00004156 uint32_t policyFlags = args.policyFlags;
4157 int32_t flags = args.flags;
4158 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004159 // InputDispatcher tracks and generates key repeats on behalf of
4160 // whatever notifies it, so repeatCount should always be set to 0
4161 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4163 policyFlags |= POLICY_FLAG_VIRTUAL;
4164 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 if (policyFlags & POLICY_FLAG_FUNCTION) {
4167 metaState |= AMETA_FUNCTION_ON;
4168 }
4169
4170 policyFlags |= POLICY_FLAG_TRUSTED;
4171
Prabir Pradhan678438e2023-04-13 19:32:51 +00004172 int32_t keyCode = args.keyCode;
4173 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004174
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004176 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4177 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4178 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Michael Wright2b3c3302018-03-02 17:19:13 +00004180 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004182 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4183 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186
Antonio Kantekf16f2832021-09-28 04:39:20 +00004187 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 { // acquire lock
4189 mLock.lock();
4190
4191 if (shouldSendKeyToInputFilterLocked(args)) {
4192 mLock.unlock();
4193
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004194 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4196 return; // event was consumed by the filter
4197 }
4198
4199 mLock.lock();
4200 }
4201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004202 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004203 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4204 args.displayId, policyFlags, args.action, flags, keyCode,
4205 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004207 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 mLock.unlock();
4209 } // release lock
4210
4211 if (needWake) {
4212 mLooper->wake();
4213 }
4214}
4215
Prabir Pradhan678438e2023-04-13 19:32:51 +00004216bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 return mInputFilterEnabled;
4218}
4219
Prabir Pradhan678438e2023-04-13 19:32:51 +00004220void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004221 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004222 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004223 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004224 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004225 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4226 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004227 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4228 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4229 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4230 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4231 args.downTime);
4232 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004233 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4234 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004235 i, args.pointerProperties[i].id,
4236 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4237 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4238 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4239 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4240 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4241 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4242 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4243 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4244 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4245 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004248
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004249 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4250 args.pointerCount, args.pointerProperties);
4251 if (!motionCheck.ok()) {
4252 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004253 return;
4254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Prabir Pradhan678438e2023-04-13 19:32:51 +00004256 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004258
4259 android::base::Timer t;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004260 mPolicy->interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004261 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4262 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
Antonio Kantekf16f2832021-09-28 04:39:20 +00004266 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 { // acquire lock
4268 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004269 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4270 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4271 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004272 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004273 if (touchStateIt != mTouchStatesByDisplay.end()) {
4274 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004275 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004276 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4277 }
4278 }
4279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
4281 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004282 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004283 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004284 displayTransform = it->second.transform;
4285 }
4286
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 mLock.unlock();
4288
4289 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004290 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4291 args.action, args.actionButton, args.flags, args.edgeFlags,
4292 args.metaState, args.buttonState, args.classification,
4293 displayTransform, args.xPrecision, args.yPrecision,
4294 args.xCursorPosition, args.yCursorPosition, displayTransform,
4295 args.downTime, args.eventTime, args.pointerCount,
4296 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297
4298 policyFlags |= POLICY_FLAG_FILTERED;
4299 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4300 return; // event was consumed by the filter
4301 }
4302
4303 mLock.lock();
4304 }
4305
4306 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004307 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004308 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4309 args.displayId, policyFlags, args.action,
4310 args.actionButton, args.flags, args.metaState,
4311 args.buttonState, args.classification, args.edgeFlags,
4312 args.xPrecision, args.yPrecision,
4313 args.xCursorPosition, args.yCursorPosition,
4314 args.downTime, args.pointerCount,
4315 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
Prabir Pradhan678438e2023-04-13 19:32:51 +00004317 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4318 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004319 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004320 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4321 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004322 }
4323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004324 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 mLock.unlock();
4326 } // release lock
4327
4328 if (needWake) {
4329 mLooper->wake();
4330 }
4331}
4332
Prabir Pradhan678438e2023-04-13 19:32:51 +00004333void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004334 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004335 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4336 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004337 args.id, args.eventTime, args.deviceId, args.source,
4338 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004339 }
Chris Yef59a2f42020-10-16 12:55:26 -07004340
Antonio Kantekf16f2832021-09-28 04:39:20 +00004341 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004342 { // acquire lock
4343 mLock.lock();
4344
4345 // Just enqueue a new sensor event.
4346 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004347 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4348 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4349 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004350
4351 needWake = enqueueInboundEventLocked(std::move(newEntry));
4352 mLock.unlock();
4353 } // release lock
4354
4355 if (needWake) {
4356 mLooper->wake();
4357 }
4358}
4359
Prabir Pradhan678438e2023-04-13 19:32:51 +00004360void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004361 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004362 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4363 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004364 }
Prabir Pradhan678438e2023-04-13 19:32:51 +00004365 mPolicy->notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004366}
4367
Prabir Pradhan678438e2023-04-13 19:32:51 +00004368bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004369 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370}
4371
Prabir Pradhan678438e2023-04-13 19:32:51 +00004372void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004373 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004374 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4375 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004376 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Prabir Pradhan678438e2023-04-13 19:32:51 +00004379 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004381 mPolicy->notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382}
4383
Prabir Pradhan678438e2023-04-13 19:32:51 +00004384void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004385 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004386 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4387 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Antonio Kantekf16f2832021-09-28 04:39:20 +00004390 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004392 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004394 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004395 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004396 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 } // release lock
4398
4399 if (needWake) {
4400 mLooper->wake();
4401 }
4402}
4403
Prabir Pradhan678438e2023-04-13 19:32:51 +00004404void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004405 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004406 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4407 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004408 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004409
Antonio Kantekf16f2832021-09-28 04:39:20 +00004410 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004411 { // acquire lock
4412 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004413 auto entry =
4414 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004415 needWake = enqueueInboundEventLocked(std::move(entry));
4416 } // release lock
4417
4418 if (needWake) {
4419 mLooper->wake();
4420 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004421}
4422
Prabir Pradhan5735a322022-04-11 17:23:34 +00004423InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4424 std::optional<int32_t> targetUid,
4425 InputEventInjectionSync syncMode,
4426 std::chrono::milliseconds timeout,
4427 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004428 Result<void> eventValidation = validateInputEvent(*event);
4429 if (!eventValidation.ok()) {
4430 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4431 return InputEventInjectionResult::FAILED;
4432 }
4433
Prabir Pradhan65613802023-02-22 23:36:58 +00004434 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004435 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4436 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4437 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4438 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004439 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004440 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441
Prabir Pradhan5735a322022-04-11 17:23:34 +00004442 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004444 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004445 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4446 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4447 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4448 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4449 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004450 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004451 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004452 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004453 }
4454
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004455 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004457 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004458 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004459 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004460 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004461 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4462 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4463 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004464 int32_t keyCode = incomingKey.getKeyCode();
4465 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004466 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004467 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004468 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004469 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004470 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4471 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4472 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4475 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004476 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004477
4478 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4479 android::base::Timer t;
4480 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4481 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4482 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4483 std::to_string(t.duration().count()).c_str());
4484 }
4485 }
4486
4487 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004488 std::unique_ptr<KeyEntry> injectedEntry =
4489 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004490 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004491 incomingKey.getDisplayId(), policyFlags, action,
4492 flags, keyCode, incomingKey.getScanCode(), metaState,
4493 incomingKey.getRepeatCount(),
4494 incomingKey.getDownTime());
4495 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 }
4498
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004499 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004500 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004501 const bool isPointerEvent =
4502 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4503 // If a pointer event has no displayId specified, inject it to the default display.
4504 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4505 ? ADISPLAY_ID_DEFAULT
4506 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004507 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004508
4509 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004510 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 android::base::Timer t;
4512 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4513 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4514 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4515 std::to_string(t.duration().count()).c_str());
4516 }
4517 }
4518
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004519 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4520 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4521 }
4522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004524 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4525 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004526 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004527 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4528 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004529 displayId, policyFlags, motionEvent.getAction(),
4530 motionEvent.getActionButton(), flags,
4531 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004532 motionEvent.getButtonState(),
4533 motionEvent.getClassification(),
4534 motionEvent.getEdgeFlags(),
4535 motionEvent.getXPrecision(),
4536 motionEvent.getYPrecision(),
4537 motionEvent.getRawXCursorPosition(),
4538 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004539 motionEvent.getDownTime(),
4540 motionEvent.getPointerCount(),
4541 motionEvent.getPointerProperties(),
4542 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004543 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004544 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004545 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004546 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004547 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004548 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004549 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4550 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004551 displayId, policyFlags,
4552 motionEvent.getAction(),
4553 motionEvent.getActionButton(), flags,
4554 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004555 motionEvent.getButtonState(),
4556 motionEvent.getClassification(),
4557 motionEvent.getEdgeFlags(),
4558 motionEvent.getXPrecision(),
4559 motionEvent.getYPrecision(),
4560 motionEvent.getRawXCursorPosition(),
4561 motionEvent.getRawYCursorPosition(),
4562 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004563 motionEvent.getPointerCount(),
4564 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004565 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004566 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4567 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004568 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569 }
4570 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004574 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004575 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 }
4577
Prabir Pradhan5735a322022-04-11 17:23:34 +00004578 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004579 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 injectionState->injectionIsAsync = true;
4581 }
4582
4583 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004584 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585
4586 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004587 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004588 if (DEBUG_INJECTION) {
4589 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4590 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004591 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004592 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 }
4594
4595 mLock.unlock();
4596
4597 if (needWake) {
4598 mLooper->wake();
4599 }
4600
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004601 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004603 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004605 if (syncMode == InputEventInjectionSync::NONE) {
4606 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 } else {
4608 for (;;) {
4609 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004610 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 break;
4612 }
4613
4614 nsecs_t remainingTimeout = endTime - now();
4615 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004616 if (DEBUG_INJECTION) {
4617 ALOGD("injectInputEvent - Timed out waiting for injection result "
4618 "to become available.");
4619 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004620 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 break;
4622 }
4623
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004624 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 }
4626
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004627 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4628 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004630 if (DEBUG_INJECTION) {
4631 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4632 injectionState->pendingForegroundDispatches);
4633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 nsecs_t remainingTimeout = endTime - now();
4635 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004636 if (DEBUG_INJECTION) {
4637 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4638 "dispatches to finish.");
4639 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004640 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 break;
4642 }
4643
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004644 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646 }
4647 }
4648
4649 injectionState->release();
4650 } // release lock
4651
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004652 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004653 LOG(DEBUG) << "injectInputEvent - Finished with result "
4654 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
4657 return injectionResult;
4658}
4659
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004660std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004661 std::array<uint8_t, 32> calculatedHmac;
4662 std::unique_ptr<VerifiedInputEvent> result;
4663 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004664 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004665 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4666 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4667 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004668 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004669 break;
4670 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004671 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004672 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4673 VerifiedMotionEvent verifiedMotionEvent =
4674 verifiedMotionEventFromMotionEvent(motionEvent);
4675 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004676 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004677 break;
4678 }
4679 default: {
4680 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4681 return nullptr;
4682 }
4683 }
4684 if (calculatedHmac == INVALID_HMAC) {
4685 return nullptr;
4686 }
tyiu1573a672023-02-21 22:38:32 +00004687 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004688 return nullptr;
4689 }
4690 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004691}
4692
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004693void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004694 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004695 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004697 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004698 LOG(DEBUG) << "Setting input event injection result to "
4699 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004702 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 // Log the outcome since the injector did not wait for the injection result.
4704 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004705 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004706 ALOGV("Asynchronous input event injection succeeded.");
4707 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004708 case InputEventInjectionResult::TARGET_MISMATCH:
4709 ALOGV("Asynchronous input event injection target mismatch.");
4710 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004711 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004712 ALOGW("Asynchronous input event injection failed.");
4713 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004714 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715 ALOGW("Asynchronous input event injection timed out.");
4716 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004717 case InputEventInjectionResult::PENDING:
4718 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4719 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 }
4721 }
4722
4723 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004724 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 }
4726}
4727
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004728void InputDispatcher::transformMotionEntryForInjectionLocked(
4729 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004730 // Input injection works in the logical display coordinate space, but the input pipeline works
4731 // display space, so we need to transform the injected events accordingly.
4732 const auto it = mDisplayInfos.find(entry.displayId);
4733 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004734 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004735
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004736 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4737 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4738 const vec2 cursor =
4739 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4740 {entry.xCursorPosition, entry.yCursorPosition});
4741 entry.xCursorPosition = cursor.x;
4742 entry.yCursorPosition = cursor.y;
4743 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004744 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004745 entry.pointerCoords[i] =
4746 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4747 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004748 }
4749}
4750
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004751void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4752 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 if (injectionState) {
4754 injectionState->pendingForegroundDispatches += 1;
4755 }
4756}
4757
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004758void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4759 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 if (injectionState) {
4761 injectionState->pendingForegroundDispatches -= 1;
4762
4763 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004764 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 }
4766 }
4767}
4768
chaviw98318de2021-05-19 16:45:23 -05004769const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004770 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004771 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004772 auto it = mWindowHandlesByDisplay.find(displayId);
4773 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004774}
4775
chaviw98318de2021-05-19 16:45:23 -05004776sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004777 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004778 if (windowHandleToken == nullptr) {
4779 return nullptr;
4780 }
4781
Arthur Hungb92218b2018-08-14 12:00:21 +08004782 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004783 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4784 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004785 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004786 return windowHandle;
4787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 }
4789 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004790 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791}
4792
chaviw98318de2021-05-19 16:45:23 -05004793sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4794 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004795 if (windowHandleToken == nullptr) {
4796 return nullptr;
4797 }
4798
chaviw98318de2021-05-19 16:45:23 -05004799 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004800 if (windowHandle->getToken() == windowHandleToken) {
4801 return windowHandle;
4802 }
4803 }
4804 return nullptr;
4805}
4806
chaviw98318de2021-05-19 16:45:23 -05004807sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4808 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004809 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004810 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4811 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004812 if (handle->getId() == windowHandle->getId() &&
4813 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004814 if (windowHandle->getInfo()->displayId != it.first) {
4815 ALOGE("Found window %s in display %" PRId32
4816 ", but it should belong to display %" PRId32,
4817 windowHandle->getName().c_str(), it.first,
4818 windowHandle->getInfo()->displayId);
4819 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004820 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
4823 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004824 return nullptr;
4825}
4826
chaviw98318de2021-05-19 16:45:23 -05004827sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004828 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4829 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830}
4831
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004832ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4833 auto displayInfoIt = mDisplayInfos.find(displayId);
4834 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4835 : kIdentityTransform;
4836}
4837
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004838bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4839 const MotionEntry& motionEntry) const {
4840 const WindowInfo& info = *window->getInfo();
4841
4842 // Skip spy window targets that are not valid for targeted injection.
4843 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004844 return false;
4845 }
4846
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004847 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4848 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4849 return false;
4850 }
4851
4852 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4853 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4854 window->getName().c_str());
4855 return false;
4856 }
4857
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004858 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004859 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004860 ALOGW("Not sending touch to %s because there's no corresponding connection",
4861 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004862 return false;
4863 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004864
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004865 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004866 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004867 return false;
4868 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004869
4870 // Drop events that can't be trusted due to occlusion
4871 const auto [x, y] = resolveTouchedPosition(motionEntry);
4872 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4873 if (!isTouchTrustedLocked(occlusionInfo)) {
4874 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004875 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004876 for (const auto& log : occlusionInfo.debugInfo) {
4877 ALOGD("%s", log.c_str());
4878 }
4879 }
4880 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4881 occlusionInfo.obscuringUid);
4882 return false;
4883 }
4884
4885 // Drop touch events if requested by input feature
4886 if (shouldDropInput(motionEntry, window)) {
4887 return false;
4888 }
4889
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004890 return true;
4891}
4892
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004893std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4894 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004895 auto connectionIt = mConnectionsByToken.find(token);
4896 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004897 return nullptr;
4898 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004899 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004900}
4901
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004902void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004903 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4904 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004905 // Remove all handles on a display if there are no windows left.
4906 mWindowHandlesByDisplay.erase(displayId);
4907 return;
4908 }
4909
4910 // Since we compare the pointer of input window handles across window updates, we need
4911 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004912 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4913 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4914 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004915 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004916 }
4917
chaviw98318de2021-05-19 16:45:23 -05004918 std::vector<sp<WindowInfoHandle>> newHandles;
4919 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004920 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004921 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004922 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004923 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004924 const bool canReceiveInput =
4925 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4926 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004927 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004928 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004929 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004930 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004931 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004932 }
4933
4934 if (info->displayId != displayId) {
4935 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4936 handle->getName().c_str(), displayId, info->displayId);
4937 continue;
4938 }
4939
Robert Carredd13602020-04-13 17:24:34 -07004940 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4941 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004942 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004943 oldHandle->updateFrom(handle);
4944 newHandles.push_back(oldHandle);
4945 } else {
4946 newHandles.push_back(handle);
4947 }
4948 }
4949
4950 // Insert or replace
4951 mWindowHandlesByDisplay[displayId] = newHandles;
4952}
4953
Arthur Hung72d8dc32020-03-28 00:48:39 +00004954void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004955 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004956 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004957 { // acquire lock
4958 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004959 for (const auto& [displayId, handles] : handlesPerDisplay) {
4960 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004961 }
4962 }
4963 // Wake up poll loop since it may need to make new input dispatching choices.
4964 mLooper->wake();
4965}
4966
Arthur Hungb92218b2018-08-14 12:00:21 +08004967/**
4968 * Called from InputManagerService, update window handle list by displayId that can receive input.
4969 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4970 * If set an empty list, remove all handles from the specific display.
4971 * For focused handle, check if need to change and send a cancel event to previous one.
4972 * For removed handle, check if need to send a cancel event if already in touch.
4973 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004974void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004975 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004976 if (DEBUG_FOCUS) {
4977 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004978 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004979 windowList += iwh->getName() + " ";
4980 }
4981 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
Prabir Pradhand65552b2021-10-07 11:23:50 -07004984 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004985 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004986 const WindowInfo& info = *window->getInfo();
4987
4988 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004989 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004990 if (noInputWindow && window->getToken() != nullptr) {
4991 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4992 window->getName().c_str());
4993 window->releaseChannel();
4994 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004995
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004996 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004997 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4998 !info.inputConfig.test(
4999 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005000 "%s has feature SPY, but is not a trusted overlay.",
5001 window->getName().c_str());
5002
Prabir Pradhand65552b2021-10-07 11:23:50 -07005003 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005004 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5005 !info.inputConfig.test(
5006 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005007 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5008 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005009 }
5010
Arthur Hung72d8dc32020-03-28 00:48:39 +00005011 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005012 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005014 // Save the old windows' orientation by ID before it gets updated.
5015 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005016 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005017 oldWindowOrientations.emplace(handle->getId(),
5018 handle->getInfo()->transform.getOrientation());
5019 }
5020
chaviw98318de2021-05-19 16:45:23 -05005021 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005022
chaviw98318de2021-05-19 16:45:23 -05005023 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005024
Vishnu Nairc519ff72021-01-21 08:23:08 -08005025 std::optional<FocusResolver::FocusChanges> changes =
5026 mFocusResolver.setInputWindows(displayId, windowHandles);
5027 if (changes) {
5028 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005031 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5032 mTouchStatesByDisplay.find(displayId);
5033 if (stateIt != mTouchStatesByDisplay.end()) {
5034 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005035 for (size_t i = 0; i < state.windows.size();) {
5036 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005037 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005038 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005039 ALOGD("Touched window was removed: %s in display %" PRId32,
5040 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005041 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005042 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005043 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5044 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005045 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005046 "touched window was removed");
5047 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005048 // Since we are about to drop the touch, cancel the events for the wallpaper as
5049 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005050 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005051 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5052 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005053 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005054 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005057 state.windows.erase(state.windows.begin() + i);
5058 } else {
5059 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
5061 }
arthurhungb89ccb02020-12-30 16:19:01 +08005062
arthurhung6d4bed92021-03-17 11:59:33 +08005063 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005064 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005065 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005066 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005067 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005068 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5069 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005070 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005071 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005072 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005073
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005074 // Determine if the orientation of any of the input windows have changed, and cancel all
5075 // pointer events if necessary.
5076 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5077 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5078 if (newWindowHandle != nullptr &&
5079 newWindowHandle->getInfo()->transform.getOrientation() !=
5080 oldWindowOrientations[oldWindowHandle->getId()]) {
5081 std::shared_ptr<InputChannel> inputChannel =
5082 getInputChannelLocked(newWindowHandle->getToken());
5083 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005084 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005085 "touched window's orientation changed");
5086 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005087 }
5088 }
5089 }
5090
Arthur Hung72d8dc32020-03-28 00:48:39 +00005091 // Release information for windows that are no longer present.
5092 // This ensures that unused input channels are released promptly.
5093 // Otherwise, they might stick around until the window handle is destroyed
5094 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005095 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005096 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005097 if (DEBUG_FOCUS) {
5098 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005099 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005100 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005101 }
chaviw291d88a2019-02-14 10:33:58 -08005102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103}
5104
5105void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005106 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005107 if (DEBUG_FOCUS) {
5108 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5109 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5110 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005111 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005112 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005113 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 } // release lock
5115
5116 // Wake up poll loop since it may need to make new input dispatching choices.
5117 mLooper->wake();
5118}
5119
Vishnu Nair599f1412021-06-21 10:39:58 -07005120void InputDispatcher::setFocusedApplicationLocked(
5121 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5122 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5123 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5124
5125 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5126 return; // This application is already focused. No need to wake up or change anything.
5127 }
5128
5129 // Set the new application handle.
5130 if (inputApplicationHandle != nullptr) {
5131 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5132 } else {
5133 mFocusedApplicationHandlesByDisplay.erase(displayId);
5134 }
5135
5136 // No matter what the old focused application was, stop waiting on it because it is
5137 // no longer focused.
5138 resetNoFocusedWindowTimeoutLocked();
5139}
5140
Tiger Huang721e26f2018-07-24 22:26:19 +08005141/**
5142 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5143 * the display not specified.
5144 *
5145 * We track any unreleased events for each window. If a window loses the ability to receive the
5146 * released event, we will send a cancel event to it. So when the focused display is changed, we
5147 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5148 * display. The display-specified events won't be affected.
5149 */
5150void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005151 if (DEBUG_FOCUS) {
5152 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5153 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005154 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005155 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005156
5157 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005158 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005159 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005160 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005161 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005162 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005163 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005164 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005165 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005166 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005167 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005168 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5169 }
5170 }
5171 mFocusedDisplayId = displayId;
5172
Chris Ye3c2d6f52020-08-09 10:39:48 -07005173 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005174 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005175 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005176
Vishnu Nairad321cd2020-08-20 16:40:21 -07005177 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005178 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005179 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005180 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005181 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005182 }
5183 }
5184 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005185 } // release lock
5186
5187 // Wake up poll loop since it may need to make new input dispatching choices.
5188 mLooper->wake();
5189}
5190
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005192 if (DEBUG_FOCUS) {
5193 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195
5196 bool changed;
5197 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005198 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199
5200 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5201 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 }
5204
5205 if (mDispatchEnabled && !enabled) {
5206 resetAndDropEverythingLocked("dispatcher is being disabled");
5207 }
5208
5209 mDispatchEnabled = enabled;
5210 mDispatchFrozen = frozen;
5211 changed = true;
5212 } else {
5213 changed = false;
5214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 } // release lock
5216
5217 if (changed) {
5218 // Wake up poll loop since it may need to make new input dispatching choices.
5219 mLooper->wake();
5220 }
5221}
5222
5223void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005224 if (DEBUG_FOCUS) {
5225 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227
5228 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005229 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230
5231 if (mInputFilterEnabled == enabled) {
5232 return;
5233 }
5234
5235 mInputFilterEnabled = enabled;
5236 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5237 } // release lock
5238
5239 // Wake up poll loop since there might be work to do to drop everything.
5240 mLooper->wake();
5241}
5242
Antonio Kanteka042c022022-07-06 16:51:07 -07005243bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5244 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005245 bool needWake = false;
5246 {
5247 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005248 ALOGD_IF(DEBUG_TOUCH_MODE,
5249 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5250 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5251 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5252 mTouchModePerDisplay.count(displayId) == 0
5253 ? "not set"
5254 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5255
Antonio Kantek15beb512022-06-13 22:35:41 +00005256 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5257 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005258 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005259 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005260 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005261 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5262 !recentWindowsAreOwnedByLocked(pid, uid)) {
5263 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5264 "window nor none of the previously interacted window",
5265 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005266 return false;
5267 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005268 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005269 mTouchModePerDisplay[displayId] = inTouchMode;
5270 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5271 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005272 needWake = enqueueInboundEventLocked(std::move(entry));
5273 } // release lock
5274
5275 if (needWake) {
5276 mLooper->wake();
5277 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005278 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005279}
5280
Antonio Kantek48710e42022-03-24 14:19:30 -07005281bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5282 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5283 if (focusedToken == nullptr) {
5284 return false;
5285 }
5286 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5287 return isWindowOwnedBy(windowHandle, pid, uid);
5288}
5289
5290bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5291 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5292 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5293 const sp<WindowInfoHandle> windowHandle =
5294 getWindowHandleLocked(connectionToken);
5295 return isWindowOwnedBy(windowHandle, pid, uid);
5296 }) != mInteractionConnectionTokens.end();
5297}
5298
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005299void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5300 if (opacity < 0 || opacity > 1) {
5301 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5302 return;
5303 }
5304
5305 std::scoped_lock lock(mLock);
5306 mMaximumObscuringOpacityForTouch = opacity;
5307}
5308
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005309std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5310InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005311 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5312 for (TouchedWindow& w : state.windows) {
5313 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005314 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005315 }
5316 }
5317 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005318 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005319}
5320
arthurhungb89ccb02020-12-30 16:19:01 +08005321bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5322 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005323 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005324 if (DEBUG_FOCUS) {
5325 ALOGD("Trivial transfer to same window.");
5326 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005327 return true;
5328 }
5329
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005331 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
Arthur Hungabbb9d82021-09-01 14:52:30 +00005333 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005334 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005335 if (state == nullptr || touchedWindow == nullptr) {
5336 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 return false;
5338 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005339
Arthur Hungabbb9d82021-09-01 14:52:30 +00005340 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5341 if (toWindowHandle == nullptr) {
5342 ALOGW("Cannot transfer focus because to window not found.");
5343 return false;
5344 }
5345
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005346 if (DEBUG_FOCUS) {
5347 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005348 touchedWindow->windowHandle->getName().c_str(),
5349 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 }
5351
Arthur Hungabbb9d82021-09-01 14:52:30 +00005352 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005353 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005354 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005355 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005356 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357
Arthur Hungabbb9d82021-09-01 14:52:30 +00005358 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005359 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005360 ftl::Flags<InputTarget::Flags> newTargetFlags =
5361 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005362 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005363 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005364 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005365 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
Arthur Hungabbb9d82021-09-01 14:52:30 +00005367 // Store the dragging window.
5368 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005369 if (pointerIds.count() != 1) {
5370 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5371 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005372 return false;
5373 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005374 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005375 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005376 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 }
5378
Arthur Hungabbb9d82021-09-01 14:52:30 +00005379 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005380 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5381 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005382 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005383 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005385 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005386 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005388 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5389 newTargetFlags);
5390
5391 // Check if the wallpaper window should deliver the corresponding event.
5392 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5393 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 } // release lock
5396
5397 // Wake up poll loop since it may need to make new input dispatching choices.
5398 mLooper->wake();
5399 return true;
5400}
5401
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005402/**
5403 * Get the touched foreground window on the given display.
5404 * Return null if there are no windows touched on that display, or if more than one foreground
5405 * window is being touched.
5406 */
5407sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5408 auto stateIt = mTouchStatesByDisplay.find(displayId);
5409 if (stateIt == mTouchStatesByDisplay.end()) {
5410 ALOGI("No touch state on display %" PRId32, displayId);
5411 return nullptr;
5412 }
5413
5414 const TouchState& state = stateIt->second;
5415 sp<WindowInfoHandle> touchedForegroundWindow;
5416 // If multiple foreground windows are touched, return nullptr
5417 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005418 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005419 if (touchedForegroundWindow != nullptr) {
5420 ALOGI("Two or more foreground windows: %s and %s",
5421 touchedForegroundWindow->getName().c_str(),
5422 window.windowHandle->getName().c_str());
5423 return nullptr;
5424 }
5425 touchedForegroundWindow = window.windowHandle;
5426 }
5427 }
5428 return touchedForegroundWindow;
5429}
5430
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005431// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005432bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005433 sp<IBinder> fromToken;
5434 { // acquire lock
5435 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005436 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005437 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005438 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5439 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005440 return false;
5441 }
5442
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005443 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5444 if (from == nullptr) {
5445 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5446 return false;
5447 }
5448
5449 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005450 } // release lock
5451
5452 return transferTouchFocus(fromToken, destChannelToken);
5453}
5454
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005456 if (DEBUG_FOCUS) {
5457 ALOGD("Resetting and dropping all events (%s).", reason);
5458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459
Michael Wrightfb04fd52022-11-24 22:31:11 +00005460 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 synthesizeCancelationEventsForAllConnectionsLocked(options);
5462
5463 resetKeyRepeatLocked();
5464 releasePendingEventLocked();
5465 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005466 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005468 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005469 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005470 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471}
5472
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005473void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005474 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 dumpDispatchStateLocked(dump);
5476
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005477 std::istringstream stream(dump);
5478 std::string line;
5479
5480 while (std::getline(stream, line, '\n')) {
5481 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483}
5484
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005485std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005486 std::string dump;
5487
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005488 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5489 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005490
5491 std::string windowName = "None";
5492 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005493 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005494 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5495 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5496 : "token has capture without window";
5497 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005498 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005499
5500 return dump;
5501}
5502
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005503void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005504 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5505 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5506 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005507 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508
Tiger Huang721e26f2018-07-24 22:26:19 +08005509 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5510 dump += StringPrintf(INDENT "FocusedApplications:\n");
5511 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5512 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005513 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005514 const std::chrono::duration timeout =
5515 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005516 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005517 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005518 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005521 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005523
Vishnu Nairc519ff72021-01-21 08:23:08 -08005524 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005525 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005527 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005528 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005529 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005530 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5531 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 }
5533 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005534 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 }
5536
arthurhung6d4bed92021-03-17 11:59:33 +08005537 if (mDragState) {
5538 dump += StringPrintf(INDENT "DragState:\n");
5539 mDragState->dump(dump, INDENT2);
5540 }
5541
Arthur Hungb92218b2018-08-14 12:00:21 +08005542 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005543 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5544 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5545 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5546 const auto& displayInfo = it->second;
5547 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5548 displayInfo.logicalHeight);
5549 displayInfo.transform.dump(dump, "transform", INDENT4);
5550 } else {
5551 dump += INDENT2 "No DisplayInfo found!\n";
5552 }
5553
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005554 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005555 dump += INDENT2 "Windows:\n";
5556 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005557 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5558 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005560 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005561 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005562 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005563 "applicationInfo.name=%s, "
5564 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005565 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005566 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005567 windowInfo->displayId,
5568 windowInfo->inputConfig.string().c_str(),
5569 windowInfo->alpha, windowInfo->frameLeft,
5570 windowInfo->frameTop, windowInfo->frameRight,
5571 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005572 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005573 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005574 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005575 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005576 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005577 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005578 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005579 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005580 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005581 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005582 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005583 }
5584 } else {
5585 dump += INDENT2 "Windows: <none>\n";
5586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 }
5588 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005589 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 }
5591
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005592 if (!mGlobalMonitorsByDisplay.empty()) {
5593 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5594 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005595 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005598 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599 }
5600
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005601 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
5603 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005604 if (!mRecentQueue.empty()) {
5605 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005606 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005607 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005608 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005609 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
5611 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005612 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
5614
5615 // Dump event currently being dispatched.
5616 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005617 dump += INDENT "PendingEvent:\n";
5618 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005619 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005620 dump += StringPrintf(", age=%" PRId64 "ms\n",
5621 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005623 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 }
5625
5626 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005627 if (!mInboundQueue.empty()) {
5628 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005629 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005630 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005631 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005632 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005635 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 }
5637
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005638 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005639 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005640 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005641 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005642 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005643 }
5644 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005645 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005646 }
5647
Prabir Pradhancef936d2021-07-21 16:17:52 +00005648 if (!mCommandQueue.empty()) {
5649 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5650 } else {
5651 dump += INDENT "CommandQueue: <empty>\n";
5652 }
5653
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005654 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005655 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005656 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005657 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005658 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005659 connection->inputChannel->getFd().get(),
5660 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005661 connection->getWindowName().c_str(),
5662 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005663 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005665 if (!connection->outboundQueue.empty()) {
5666 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5667 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005668 dump += dumpQueue(connection->outboundQueue, currentTime);
5669
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005671 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672 }
5673
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005674 if (!connection->waitQueue.empty()) {
5675 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5676 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005677 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005679 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680 }
5681 }
5682 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685
5686 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005687 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5688 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005690 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 }
5692
Antonio Kantek15beb512022-06-13 22:35:41 +00005693 if (!mTouchModePerDisplay.empty()) {
5694 dump += INDENT "TouchModePerDisplay:\n";
5695 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5696 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5697 std::to_string(touchMode).c_str());
5698 }
5699 } else {
5700 dump += INDENT "TouchModePerDisplay: <none>\n";
5701 }
5702
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005703 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005704 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5705 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5706 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005707 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005708 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709}
5710
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005711void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005712 const size_t numMonitors = monitors.size();
5713 for (size_t i = 0; i < numMonitors; i++) {
5714 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005715 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005716 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5717 dump += "\n";
5718 }
5719}
5720
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005721class LooperEventCallback : public LooperCallback {
5722public:
5723 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5724 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5725
5726private:
5727 std::function<int(int events)> mCallback;
5728};
5729
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005730Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005731 if (DEBUG_CHANNEL_CREATION) {
5732 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005734
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005735 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005736 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005737 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005738
5739 if (result) {
5740 return base::Error(result) << "Failed to open input channel pair with name " << name;
5741 }
5742
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005744 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005745 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005746 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005747 std::shared_ptr<Connection> connection =
5748 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5749 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005751 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5752 ALOGE("Created a new connection, but the token %p is already known", token.get());
5753 }
5754 mConnectionsByToken.emplace(token, connection);
5755
5756 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5757 this, std::placeholders::_1, token);
5758
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005759 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5760 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761 } // release lock
5762
5763 // Wake the looper because some connections have changed.
5764 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005765 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766}
5767
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005768Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005769 const std::string& name,
5770 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005771 std::shared_ptr<InputChannel> serverChannel;
5772 std::unique_ptr<InputChannel> clientChannel;
5773 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5774 if (result) {
5775 return base::Error(result) << "Failed to open input channel pair with name " << name;
5776 }
5777
Michael Wright3dd60e22019-03-27 22:06:44 +00005778 { // acquire lock
5779 std::scoped_lock _l(mLock);
5780
5781 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005782 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5783 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005784 }
5785
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005786 std::shared_ptr<Connection> connection =
5787 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005788 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005789 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005790
5791 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5792 ALOGE("Created a new connection, but the token %p is already known", token.get());
5793 }
5794 mConnectionsByToken.emplace(token, connection);
5795 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5796 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005797
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005798 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005799
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005800 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5801 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005802 }
Garfield Tan15601662020-09-22 15:32:38 -07005803
Michael Wright3dd60e22019-03-27 22:06:44 +00005804 // Wake the looper because some connections have changed.
5805 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005806 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005807}
5808
Garfield Tan15601662020-09-22 15:32:38 -07005809status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005811 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812
Harry Cutts33476232023-01-30 19:57:29 +00005813 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 if (status) {
5815 return status;
5816 }
5817 } // release lock
5818
5819 // Wake the poll loop because removing the connection may have changed the current
5820 // synchronization state.
5821 mLooper->wake();
5822 return OK;
5823}
5824
Garfield Tan15601662020-09-22 15:32:38 -07005825status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5826 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005827 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005828 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005829 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 return BAD_VALUE;
5831 }
5832
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005833 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005834
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005836 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 }
5838
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005839 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840
5841 nsecs_t currentTime = now();
5842 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5843
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005844 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 return OK;
5846}
5847
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005848void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005849 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5850 auto& [displayId, monitors] = *it;
5851 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5852 return monitor.inputChannel->getConnectionToken() == connectionToken;
5853 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005854
Michael Wright3dd60e22019-03-27 22:06:44 +00005855 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005856 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005857 } else {
5858 ++it;
5859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 }
5861}
5862
Michael Wright3dd60e22019-03-27 22:06:44 +00005863status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005864 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005865 return pilferPointersLocked(token);
5866}
Michael Wright3dd60e22019-03-27 22:06:44 +00005867
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005868status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005869 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5870 if (!requestingChannel) {
5871 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5872 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005873 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005874
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005875 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005876 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005877 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5878 " Ignoring.");
5879 return BAD_VALUE;
5880 }
5881
5882 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005883 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005884 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005885 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005886 "input channel stole pointer stream");
5887 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005888 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005889 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005890 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005891 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005892 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005893 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005894 if (channel != nullptr && channel->getConnectionToken() != token) {
5895 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5896 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5897 canceledWindows += channel->getName();
5898 }
5899 }
5900 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5901 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5902 canceledWindows.c_str());
5903
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005904 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005905 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005906 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005907
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005908 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005909 return OK;
5910}
5911
Prabir Pradhan99987712020-11-10 18:43:05 -08005912void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5913 { // acquire lock
5914 std::scoped_lock _l(mLock);
5915 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005916 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005917 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5918 windowHandle != nullptr ? windowHandle->getName().c_str()
5919 : "token without window");
5920 }
5921
Vishnu Nairc519ff72021-01-21 08:23:08 -08005922 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005923 if (focusedToken != windowToken) {
5924 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5925 enabled ? "enable" : "disable");
5926 return;
5927 }
5928
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005929 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005930 ALOGW("Ignoring request to %s Pointer Capture: "
5931 "window has %s requested pointer capture.",
5932 enabled ? "enable" : "disable", enabled ? "already" : "not");
5933 return;
5934 }
5935
Christine Franksb768bb42021-11-29 12:11:31 -08005936 if (enabled) {
5937 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5938 mIneligibleDisplaysForPointerCapture.end(),
5939 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5940 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5941 return;
5942 }
5943 }
5944
Prabir Pradhan99987712020-11-10 18:43:05 -08005945 setPointerCaptureLocked(enabled);
5946 } // release lock
5947
5948 // Wake the thread to process command entries.
5949 mLooper->wake();
5950}
5951
Christine Franksb768bb42021-11-29 12:11:31 -08005952void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5953 { // acquire lock
5954 std::scoped_lock _l(mLock);
5955 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5956 if (!isEligible) {
5957 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5958 }
5959 } // release lock
5960}
5961
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005962std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5963 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005964 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005965 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005966 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005967 }
5968 }
5969 }
5970 return std::nullopt;
5971}
5972
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005973std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
5974 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005975 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005976 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005977 }
5978
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005979 for (const auto& [token, connection] : mConnectionsByToken) {
5980 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005981 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 }
5983 }
Robert Carr4e670e52018-08-15 13:26:12 -07005984
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005985 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986}
5987
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005988std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005989 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005990 if (connection == nullptr) {
5991 return "<nullptr>";
5992 }
5993 return connection->getInputChannelName();
5994}
5995
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005996void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005997 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005998 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005999}
6000
Prabir Pradhancef936d2021-07-21 16:17:52 +00006001void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006002 const std::shared_ptr<Connection>& connection,
6003 uint32_t seq, bool handled,
6004 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006005 // Handle post-event policy actions.
6006 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6007 if (dispatchEntryIt == connection->waitQueue.end()) {
6008 return;
6009 }
6010 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6011 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6012 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6013 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6014 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6015 }
6016 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6017 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6018 connection->inputChannel->getConnectionToken(),
6019 dispatchEntry->deliveryTime, consumeTime, finishTime);
6020 }
6021
6022 bool restartEvent;
6023 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6024 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6025 restartEvent =
6026 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6027 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6028 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6029 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6030 handled);
6031 } else {
6032 restartEvent = false;
6033 }
6034
6035 // Dequeue the event and start the next cycle.
6036 // Because the lock might have been released, it is possible that the
6037 // contents of the wait queue to have been drained, so we need to double-check
6038 // a few things.
6039 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6040 if (dispatchEntryIt != connection->waitQueue.end()) {
6041 dispatchEntry = *dispatchEntryIt;
6042 connection->waitQueue.erase(dispatchEntryIt);
6043 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6044 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6045 if (!connection->responsive) {
6046 connection->responsive = isConnectionResponsive(*connection);
6047 if (connection->responsive) {
6048 // The connection was unresponsive, and now it's responsive.
6049 processConnectionResponsiveLocked(*connection);
6050 }
6051 }
6052 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006053 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006054 connection->outboundQueue.push_front(dispatchEntry);
6055 traceOutboundQueueLength(*connection);
6056 } else {
6057 releaseDispatchEntry(dispatchEntry);
6058 }
6059 }
6060
6061 // Start the next dispatch cycle for this connection.
6062 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063}
6064
Prabir Pradhancef936d2021-07-21 16:17:52 +00006065void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6066 const sp<IBinder>& newToken) {
6067 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6068 scoped_unlock unlock(mLock);
6069 mPolicy->notifyFocusChanged(oldToken, newToken);
6070 };
6071 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072}
6073
Prabir Pradhancef936d2021-07-21 16:17:52 +00006074void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6075 auto command = [this, token, x, y]() REQUIRES(mLock) {
6076 scoped_unlock unlock(mLock);
6077 mPolicy->notifyDropWindow(token, x, y);
6078 };
6079 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006080}
6081
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006082void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006083 if (connection == nullptr) {
6084 LOG_ALWAYS_FATAL("Caller must check for nullness");
6085 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006086 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6087 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006088 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006089 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006090 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006091 return;
6092 }
6093 /**
6094 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6095 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6096 * has changed. This could cause newer entries to time out before the already dispatched
6097 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6098 * processes the events linearly. So providing information about the oldest entry seems to be
6099 * most useful.
6100 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006101 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006102 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6103 std::string reason =
6104 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006105 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006106 ns2ms(currentWait),
6107 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006108 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006109 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006110
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006111 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6112
6113 // Stop waking up for events on this connection, it is already unresponsive
6114 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006115}
6116
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006117void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6118 std::string reason =
6119 StringPrintf("%s does not have a focused window", application->getName().c_str());
6120 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006121
Prabir Pradhancef936d2021-07-21 16:17:52 +00006122 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6123 scoped_unlock unlock(mLock);
6124 mPolicy->notifyNoFocusedWindowAnr(application);
6125 };
6126 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006127}
6128
chaviw98318de2021-05-19 16:45:23 -05006129void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006130 const std::string& reason) {
6131 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6132 updateLastAnrStateLocked(windowLabel, reason);
6133}
6134
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006135void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6136 const std::string& reason) {
6137 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006138 updateLastAnrStateLocked(windowLabel, reason);
6139}
6140
6141void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6142 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006143 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006144 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145 struct tm tm;
6146 localtime_r(&t, &tm);
6147 char timestr[64];
6148 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006149 mLastAnrState.clear();
6150 mLastAnrState += INDENT "ANR:\n";
6151 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006152 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6153 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006154 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006155}
6156
Prabir Pradhancef936d2021-07-21 16:17:52 +00006157void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6158 KeyEntry& entry) {
6159 const KeyEvent event = createKeyEvent(entry);
6160 nsecs_t delay = 0;
6161 { // release lock
6162 scoped_unlock unlock(mLock);
6163 android::base::Timer t;
6164 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6165 entry.policyFlags);
6166 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6167 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6168 std::to_string(t.duration().count()).c_str());
6169 }
6170 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171
6172 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006173 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006174 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006175 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006177 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006178 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180}
6181
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006183 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006184 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006185 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006186 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006187 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006188 };
6189 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006190}
6191
Prabir Pradhanedd96402022-02-15 01:46:16 -08006192void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6193 std::optional<int32_t> pid) {
6194 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006195 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006196 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006197 };
6198 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006199}
6200
6201/**
6202 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6203 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6204 * command entry to the command queue.
6205 */
6206void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6207 std::string reason) {
6208 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006209 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006210 if (connection.monitor) {
6211 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6212 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006213 pid = findMonitorPidByTokenLocked(connectionToken);
6214 } else {
6215 // The connection is a window
6216 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6217 reason.c_str());
6218 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6219 if (handle != nullptr) {
6220 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006221 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006222 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006223 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006224}
6225
6226/**
6227 * Tell the policy that a connection has become responsive so that it can stop ANR.
6228 */
6229void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6230 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006231 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006232 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006233 pid = findMonitorPidByTokenLocked(connectionToken);
6234 } else {
6235 // The connection is a window
6236 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6237 if (handle != nullptr) {
6238 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006239 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006240 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006241 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006242}
6243
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006244bool InputDispatcher::afterKeyEventLockedInterruptable(
6245 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6246 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006247 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006248 if (!handled) {
6249 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006250 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006251 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006252 return false;
6253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006255 // Get the fallback key state.
6256 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006257 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006258 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006259 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006260 connection->inputState.removeFallbackKey(originalKeyCode);
6261 }
6262
6263 if (handled || !dispatchEntry->hasForegroundTarget()) {
6264 // If the application handles the original key for which we previously
6265 // generated a fallback or if the window is not a foreground window,
6266 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006267 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006268 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006269 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6270 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6271 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6272 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6273 keyEntry.policyFlags);
6274 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006275 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006276 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277
6278 mLock.unlock();
6279
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006280 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006281 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282
6283 mLock.lock();
6284
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006285 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006286 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006287 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006288 "application handled the original non-fallback key "
6289 "or is no longer a foreground target, "
6290 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006291 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006293 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006294 connection->inputState.removeFallbackKey(originalKeyCode);
6295 }
6296 } else {
6297 // If the application did not handle a non-fallback key, first check
6298 // that we are in a good state to perform unhandled key event processing
6299 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006300 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006301 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006302 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6303 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6304 "since this is not an initial down. "
6305 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6306 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6307 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006308 return false;
6309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006310
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006311 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006312 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6313 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6314 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6315 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6316 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006317 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006318
6319 mLock.unlock();
6320
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006321 bool fallback =
6322 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006323 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006324
6325 mLock.lock();
6326
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006327 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006328 connection->inputState.removeFallbackKey(originalKeyCode);
6329 return false;
6330 }
6331
6332 // Latch the fallback keycode for this key on an initial down.
6333 // The fallback keycode cannot change at any other point in the lifecycle.
6334 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006336 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006337 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006338 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006339 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006340 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006341 }
6342
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006343 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006344
6345 // Cancel the fallback key if the policy decides not to send it anymore.
6346 // We will continue to dispatch the key to the policy but we will no
6347 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006348 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6349 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006350 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6351 if (fallback) {
6352 ALOGD("Unhandled key event: Policy requested to send key %d"
6353 "as a fallback for %d, but on the DOWN it had requested "
6354 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006355 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006356 } else {
6357 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6358 "but on the DOWN it had requested to send %d. "
6359 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006360 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006361 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006362 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006363
Michael Wrightfb04fd52022-11-24 22:31:11 +00006364 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006365 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006366 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006367 synthesizeCancelationEventsForConnectionLocked(connection, options);
6368
6369 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006370 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006371 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006372 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006373 }
6374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006375
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006376 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6377 {
6378 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006379 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006380 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006381 for (const auto& [key, value] : fallbackKeys) {
6382 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006383 }
6384 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6385 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006387 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006388
6389 if (fallback) {
6390 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006391 keyEntry.eventTime = event.getEventTime();
6392 keyEntry.deviceId = event.getDeviceId();
6393 keyEntry.source = event.getSource();
6394 keyEntry.displayId = event.getDisplayId();
6395 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006396 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006397 keyEntry.scanCode = event.getScanCode();
6398 keyEntry.metaState = event.getMetaState();
6399 keyEntry.repeatCount = event.getRepeatCount();
6400 keyEntry.downTime = event.getDownTime();
6401 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006402
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006403 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6404 ALOGD("Unhandled key event: Dispatching fallback key. "
6405 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006406 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006407 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 return true; // restart the event
6409 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006410 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6411 ALOGD("Unhandled key event: No fallback key.");
6412 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006413
6414 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006415 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 }
6417 }
6418 return false;
6419}
6420
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006421bool InputDispatcher::afterMotionEventLockedInterruptable(
6422 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6423 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424 return false;
6425}
6426
Michael Wrightd02c5b62014-02-10 15:10:22 -08006427void InputDispatcher::traceInboundQueueLengthLocked() {
6428 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006429 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430 }
6431}
6432
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006433void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006434 if (ATRACE_ENABLED()) {
6435 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006436 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6437 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 }
6439}
6440
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006441void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442 if (ATRACE_ENABLED()) {
6443 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006444 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6445 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 }
6447}
6448
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006449void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006452 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453 dumpDispatchStateLocked(dump);
6454
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006455 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006456 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006457 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006458 }
6459}
6460
6461void InputDispatcher::monitor() {
6462 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006463 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006464 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006465 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006466}
6467
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006468/**
6469 * Wake up the dispatcher and wait until it processes all events and commands.
6470 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6471 * this method can be safely called from any thread, as long as you've ensured that
6472 * the work you are interested in completing has already been queued.
6473 */
6474bool InputDispatcher::waitForIdle() {
6475 /**
6476 * Timeout should represent the longest possible time that a device might spend processing
6477 * events and commands.
6478 */
6479 constexpr std::chrono::duration TIMEOUT = 100ms;
6480 std::unique_lock lock(mLock);
6481 mLooper->wake();
6482 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6483 return result == std::cv_status::no_timeout;
6484}
6485
Vishnu Naire798b472020-07-23 13:52:21 -07006486/**
6487 * Sets focus to the window identified by the token. This must be called
6488 * after updating any input window handles.
6489 *
6490 * Params:
6491 * request.token - input channel token used to identify the window that should gain focus.
6492 * request.focusedToken - the token that the caller expects currently to be focused. If the
6493 * specified token does not match the currently focused window, this request will be dropped.
6494 * If the specified focused token matches the currently focused window, the call will succeed.
6495 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6496 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6497 * when requesting the focus change. This determines which request gets
6498 * precedence if there is a focus change request from another source such as pointer down.
6499 */
Vishnu Nair958da932020-08-21 17:12:37 -07006500void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6501 { // acquire lock
6502 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006503 std::optional<FocusResolver::FocusChanges> changes =
6504 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6505 if (changes) {
6506 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006507 }
6508 } // release lock
6509 // Wake up poll loop since it may need to make new input dispatching choices.
6510 mLooper->wake();
6511}
6512
Vishnu Nairc519ff72021-01-21 08:23:08 -08006513void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6514 if (changes.oldFocus) {
6515 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006516 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006517 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006518 "focus left window");
6519 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006520 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006521 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006522 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006523 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006524 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006525 }
6526
Prabir Pradhan99987712020-11-10 18:43:05 -08006527 // If a window has pointer capture, then it must have focus. We need to ensure that this
6528 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6529 // If the window loses focus before it loses pointer capture, then the window can be in a state
6530 // where it has pointer capture but not focus, violating the contract. Therefore we must
6531 // dispatch the pointer capture event before the focus event. Since focus events are added to
6532 // the front of the queue (above), we add the pointer capture event to the front of the queue
6533 // after the focus events are added. This ensures the pointer capture event ends up at the
6534 // front.
6535 disablePointerCaptureForcedLocked();
6536
Vishnu Nairc519ff72021-01-21 08:23:08 -08006537 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006538 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006539 }
6540}
Vishnu Nair958da932020-08-21 17:12:37 -07006541
Prabir Pradhan99987712020-11-10 18:43:05 -08006542void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006543 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006544 return;
6545 }
6546
6547 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6548
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006549 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006550 setPointerCaptureLocked(false);
6551 }
6552
6553 if (!mWindowTokenWithPointerCapture) {
6554 // No need to send capture changes because no window has capture.
6555 return;
6556 }
6557
6558 if (mPendingEvent != nullptr) {
6559 // Move the pending event to the front of the queue. This will give the chance
6560 // for the pending event to be dropped if it is a captured event.
6561 mInboundQueue.push_front(mPendingEvent);
6562 mPendingEvent = nullptr;
6563 }
6564
6565 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006566 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006567 mInboundQueue.push_front(std::move(entry));
6568}
6569
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006570void InputDispatcher::setPointerCaptureLocked(bool enable) {
6571 mCurrentPointerCaptureRequest.enable = enable;
6572 mCurrentPointerCaptureRequest.seq++;
6573 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006574 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006575 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006576 };
6577 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006578}
6579
Vishnu Nair599f1412021-06-21 10:39:58 -07006580void InputDispatcher::displayRemoved(int32_t displayId) {
6581 { // acquire lock
6582 std::scoped_lock _l(mLock);
6583 // Set an empty list to remove all handles from the specific display.
6584 setInputWindowsLocked(/* window handles */ {}, displayId);
6585 setFocusedApplicationLocked(displayId, nullptr);
6586 // Call focus resolver to clean up stale requests. This must be called after input windows
6587 // have been removed for the removed display.
6588 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006589 // Reset pointer capture eligibility, regardless of previous state.
6590 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006591 // Remove the associated touch mode state.
6592 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006593 } // release lock
6594
6595 // Wake up poll loop since it may need to make new input dispatching choices.
6596 mLooper->wake();
6597}
6598
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006599void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6600 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006601 // The listener sends the windows as a flattened array. Separate the windows by display for
6602 // more convenient parsing.
6603 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006604 for (const auto& info : windowInfos) {
6605 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006606 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006607 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006608
6609 { // acquire lock
6610 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006611
6612 // Ensure that we have an entry created for all existing displays so that if a displayId has
6613 // no windows, we can tell that the windows were removed from the display.
6614 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6615 handlesPerDisplay[displayId];
6616 }
6617
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006618 mDisplayInfos.clear();
6619 for (const auto& displayInfo : displayInfos) {
6620 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6621 }
6622
6623 for (const auto& [displayId, handles] : handlesPerDisplay) {
6624 setInputWindowsLocked(handles, displayId);
6625 }
6626 }
6627 // Wake up poll loop since it may need to make new input dispatching choices.
6628 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006629}
6630
Vishnu Nair062a8672021-09-03 16:07:44 -07006631bool InputDispatcher::shouldDropInput(
6632 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006633 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6634 (windowHandle->getInfo()->inputConfig.test(
6635 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006636 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006637 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6638 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006639 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006640 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006641 windowHandle->getInfo()->displayId);
6642 return true;
6643 }
6644 return false;
6645}
6646
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006647void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6648 const std::vector<gui::WindowInfo>& windowInfos,
6649 const std::vector<DisplayInfo>& displayInfos) {
6650 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6651}
6652
Arthur Hungdfd528e2021-12-08 13:23:04 +00006653void InputDispatcher::cancelCurrentTouch() {
6654 {
6655 std::scoped_lock _l(mLock);
6656 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006657 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006658 "cancel current touch");
6659 synthesizeCancelationEventsForAllConnectionsLocked(options);
6660
6661 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006662 }
6663 // Wake up poll loop since there might be work to do.
6664 mLooper->wake();
6665}
6666
Prabir Pradhan87112a72023-04-20 19:13:39 +00006667void InputDispatcher::requestRefreshConfiguration() {
6668 InputDispatcherConfiguration config;
6669 mPolicy->getDispatcherConfiguration(&config);
6670
6671 std::scoped_lock _l(mLock);
6672 mConfig = config;
6673}
6674
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006675void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6676 std::scoped_lock _l(mLock);
6677 mMonitorDispatchingTimeout = timeout;
6678}
6679
Arthur Hungc539dbb2022-12-08 07:45:36 +00006680void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6681 const sp<WindowInfoHandle>& oldWindowHandle,
6682 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006683 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006684 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006685 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6686 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006687 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6688 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6689 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6690 newWindowHandle->getInfo()->inputConfig.test(
6691 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6692 const sp<WindowInfoHandle> oldWallpaper =
6693 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6694 const sp<WindowInfoHandle> newWallpaper =
6695 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6696 if (oldWallpaper == newWallpaper) {
6697 return;
6698 }
6699
6700 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006701 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6702 addWindowTargetLocked(oldWallpaper,
6703 oldTouchedWindow.targetFlags |
6704 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6705 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6706 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006707 }
6708
6709 if (newWallpaper != nullptr) {
6710 state.addOrUpdateWindow(newWallpaper,
6711 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6712 InputTarget::Flags::WINDOW_IS_OBSCURED |
6713 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6714 pointerIds);
6715 }
6716}
6717
6718void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6719 ftl::Flags<InputTarget::Flags> newTargetFlags,
6720 const sp<WindowInfoHandle> fromWindowHandle,
6721 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006722 TouchState& state,
6723 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006724 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6725 fromWindowHandle->getInfo()->inputConfig.test(
6726 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6727 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6728 toWindowHandle->getInfo()->inputConfig.test(
6729 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6730
6731 const sp<WindowInfoHandle> oldWallpaper =
6732 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6733 const sp<WindowInfoHandle> newWallpaper =
6734 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6735 if (oldWallpaper == newWallpaper) {
6736 return;
6737 }
6738
6739 if (oldWallpaper != nullptr) {
6740 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6741 "transferring touch focus to another window");
6742 state.removeWindowByToken(oldWallpaper->getToken());
6743 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6744 }
6745
6746 if (newWallpaper != nullptr) {
6747 nsecs_t downTimeInTarget = now();
6748 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6749 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6750 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6751 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6752 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006753 std::shared_ptr<Connection> wallpaperConnection =
6754 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006755 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006756 std::shared_ptr<Connection> toConnection =
6757 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006758 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6759 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6760 wallpaperFlags);
6761 }
6762 }
6763}
6764
6765sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6766 const sp<WindowInfoHandle>& windowHandle) const {
6767 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6768 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6769 bool foundWindow = false;
6770 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6771 if (!foundWindow && otherHandle != windowHandle) {
6772 continue;
6773 }
6774 if (windowHandle == otherHandle) {
6775 foundWindow = true;
6776 continue;
6777 }
6778
6779 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6780 return otherHandle;
6781 }
6782 }
6783 return nullptr;
6784}
6785
Garfield Tane84e6f92019-08-29 17:28:41 -07006786} // namespace android::inputdispatcher