blob: a3c129e31a559a8505452998684b0f1b15c36d00 [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
Harry Cuttsb166c002023-05-09 13:06:05 +0000684// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
685// both.
686void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
687 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
688 if (!window.windowHandle->getInfo()->inputConfig.test(
689 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
690 // In addition to TouchState, erase this window from the input targets! We don't have a
691 // good way to do this today except by adding a nested loop.
692 // TODO(b/282025641): simplify this code once InputTargets are being identified
693 // separately from TouchedWindows.
694 std::erase_if(targets, [&](const InputTarget& target) {
695 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
696 });
697 return true;
698 }
699 return false;
700 });
701}
702
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000703} // namespace
704
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705// --- InputDispatcher ---
706
Prabir Pradhana41d2442023-04-20 21:30:40 +0000707InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800708 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
709
Prabir Pradhana41d2442023-04-20 21:30:40 +0000710InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800711 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700712 : mPolicy(policy),
713 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700714 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800715 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700716 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700717 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700718 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800719 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700720 mDispatchEnabled(false),
721 mDispatchFrozen(false),
722 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100723 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000724 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800725 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800726 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000727 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000728 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700729 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800730 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700732 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700733#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700734 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700735#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700736 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737}
738
739InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000740 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741
Prabir Pradhancef936d2021-07-21 16:17:52 +0000742 resetKeyRepeatLocked();
743 releasePendingEventLocked();
744 drainInboundQueueLocked();
745 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000747 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700748 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000749 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
751}
752
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700753status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700754 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700755 return ALREADY_EXISTS;
756 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700757 mThread = std::make_unique<InputThread>(
758 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
759 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700760}
761
762status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700763 if (mThread && mThread->isCallingThread()) {
764 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700765 return INVALID_OPERATION;
766 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700767 mThread.reset();
768 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700769}
770
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700772 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800774 std::scoped_lock _l(mLock);
775 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776
777 // Run a dispatch loop if there are no pending commands.
778 // The dispatch loop might enqueue commands to run afterwards.
779 if (!haveCommandsLocked()) {
780 dispatchOnceInnerLocked(&nextWakeupTime);
781 }
782
783 // Run all pending commands if there are any.
784 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000785 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700786 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800788
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700789 // If we are still waiting for ack on some events,
790 // we might have to wake up earlier to check if an app is anr'ing.
791 const nsecs_t nextAnrCheck = processAnrsLocked();
792 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
793
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800794 // We are about to enter an infinitely long sleep, because we have no commands or
795 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700796 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800797 mDispatcherEnteredIdle.notify_all();
798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 } // release lock
800
801 // Wait for callback or timeout or wake. (make sure we round up, not down)
802 nsecs_t currentTime = now();
803 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
804 mLooper->pollOnce(timeoutMillis);
805}
806
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700807/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500808 * Raise ANR if there is no focused window.
809 * Before the ANR is raised, do a final state check:
810 * 1. The currently focused application must be the same one we are waiting for.
811 * 2. Ensure we still don't have a focused window.
812 */
813void InputDispatcher::processNoFocusedWindowAnrLocked() {
814 // Check if the application that we are waiting for is still focused.
815 std::shared_ptr<InputApplicationHandle> focusedApplication =
816 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
817 if (focusedApplication == nullptr ||
818 focusedApplication->getApplicationToken() !=
819 mAwaitedFocusedApplication->getApplicationToken()) {
820 // Unexpected because we should have reset the ANR timer when focused application changed
821 ALOGE("Waited for a focused window, but focused application has already changed to %s",
822 focusedApplication->getName().c_str());
823 return; // The focused application has changed.
824 }
825
chaviw98318de2021-05-19 16:45:23 -0500826 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500827 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
828 if (focusedWindowHandle != nullptr) {
829 return; // We now have a focused window. No need for ANR.
830 }
831 onAnrLocked(mAwaitedFocusedApplication);
832}
833
834/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700835 * Check if any of the connections' wait queues have events that are too old.
836 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
837 * Return the time at which we should wake up next.
838 */
839nsecs_t InputDispatcher::processAnrsLocked() {
840 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700841 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700842 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
843 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
844 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500845 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700846 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500847 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700848 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700849 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500850 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700851 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
852 }
853 }
854
855 // Check if any connection ANRs are due
856 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
857 if (currentTime < nextAnrCheck) { // most likely scenario
858 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
859 }
860
861 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700862 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700863 if (connection == nullptr) {
864 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
865 return nextAnrCheck;
866 }
867 connection->responsive = false;
868 // Stop waking up for this unresponsive connection
869 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000870 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700871 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700872}
873
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800874std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700875 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800876 if (connection->monitor) {
877 return mMonitorDispatchingTimeout;
878 }
879 const sp<WindowInfoHandle> window =
880 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700881 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500882 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700883 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500884 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700885}
886
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
888 nsecs_t currentTime = now();
889
Jeff Browndc5992e2014-04-11 01:27:26 -0700890 // Reset the key repeat timer whenever normal dispatch is suspended while the
891 // device is in a non-interactive state. This is to ensure that we abort a key
892 // repeat if the device is just coming out of sleep.
893 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 resetKeyRepeatLocked();
895 }
896
897 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
898 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100899 if (DEBUG_FOCUS) {
900 ALOGD("Dispatch frozen. Waiting some more.");
901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 return;
903 }
904
905 // Optimize latency of app switches.
906 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
907 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
908 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
909 if (mAppSwitchDueTime < *nextWakeupTime) {
910 *nextWakeupTime = mAppSwitchDueTime;
911 }
912
913 // Ready to start a new event.
914 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700916 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 if (isAppSwitchDue) {
918 // The inbound queue is empty so the app switch key we were waiting
919 // for will never arrive. Stop waiting for it.
920 resetPendingAppSwitchLocked(false);
921 isAppSwitchDue = false;
922 }
923
924 // Synthesize a key repeat if appropriate.
925 if (mKeyRepeatState.lastKeyEntry) {
926 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
927 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
928 } else {
929 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
930 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
931 }
932 }
933 }
934
935 // Nothing to do if there is no pending event.
936 if (!mPendingEvent) {
937 return;
938 }
939 } else {
940 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700941 mPendingEvent = mInboundQueue.front();
942 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 traceInboundQueueLengthLocked();
944 }
945
946 // Poke user activity for this event.
947 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700948 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 }
951
952 // Now we have an event to dispatch.
953 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700954 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700956 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700958 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700960 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 }
962
963 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700964 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 }
966
967 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700968 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700969 const ConfigurationChangedEntry& typedEntry =
970 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700971 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 break;
974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700976 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977 const DeviceResetEntry& typedEntry =
978 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700980 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 break;
982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100984 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985 std::shared_ptr<FocusEntry> typedEntry =
986 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100987 dispatchFocusLocked(currentTime, typedEntry);
988 done = true;
989 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
990 break;
991 }
992
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700993 case EventEntry::Type::TOUCH_MODE_CHANGED: {
994 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
995 dispatchTouchModeChangeLocked(currentTime, typedEntry);
996 done = true;
997 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
998 break;
999 }
1000
Prabir Pradhan99987712020-11-10 18:43:05 -08001001 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1002 const auto typedEntry =
1003 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1004 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1005 done = true;
1006 break;
1007 }
1008
arthurhungb89ccb02020-12-30 16:19:01 +08001009 case EventEntry::Type::DRAG: {
1010 std::shared_ptr<DragEntry> typedEntry =
1011 std::static_pointer_cast<DragEntry>(mPendingEvent);
1012 dispatchDragLocked(currentTime, typedEntry);
1013 done = true;
1014 break;
1015 }
1016
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 resetPendingAppSwitchLocked(true);
1022 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 } else if (dropReason == DropReason::NOT_DROPPED) {
1024 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 }
1026 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001027 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001030 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1031 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 break;
1035 }
1036
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001037 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001038 std::shared_ptr<MotionEntry> motionEntry =
1039 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001040 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1041 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001043 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001044 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1047 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
Chris Yef59a2f42020-10-16 12:55:26 -07001052
1053 case EventEntry::Type::SENSOR: {
1054 std::shared_ptr<SensorEntry> sensorEntry =
1055 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1056 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1057 dropReason = DropReason::APP_SWITCH;
1058 }
1059 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1060 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1061 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1062 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1063 dropReason = DropReason::STALE;
1064 }
1065 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1066 done = true;
1067 break;
1068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 }
1070
1071 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001073 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
Michael Wright3a981722015-06-10 15:26:13 +01001075 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076
1077 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001078 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080}
1081
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001082bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1083 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1084}
1085
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001086/**
1087 * Return true if the events preceding this incoming motion event should be dropped
1088 * Return false otherwise (the default behaviour)
1089 */
1090bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001091 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001092 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001093
1094 // Optimize case where the current application is unresponsive and the user
1095 // decides to touch a window in a different application.
1096 // If the application takes too long to catch up then we drop all events preceding
1097 // the touch into the other window.
1098 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001099 const int32_t displayId = motionEntry.displayId;
1100 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001101 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001102
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001103 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001104 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001105 touchedWindowHandle->getApplicationToken() !=
1106 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001107 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001108 ALOGI("Pruning input queue because user touched a different application while waiting "
1109 "for %s",
1110 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001111 return true;
1112 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001113
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001114 // Alternatively, maybe there's a spy window that could handle this event.
1115 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1116 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1117 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001118 const std::shared_ptr<Connection> connection =
1119 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001120 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001121 // This spy window could take more input. Drop all events preceding this
1122 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001123 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001124 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001125 mAwaitedFocusedApplication->getName().c_str());
1126 return true;
1127 }
1128 }
1129 }
1130
1131 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1132 // yet been processed by some connections, the dispatcher will wait for these motion
1133 // events to be processed before dispatching the key event. This is because these motion events
1134 // may cause a new window to be launched, which the user might expect to receive focus.
1135 // To prevent waiting forever for such events, just send the key to the currently focused window
1136 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1137 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1138 "just send the pending key event to the focused window.");
1139 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001140 }
1141 return false;
1142}
1143
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001144bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001145 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 mInboundQueue.push_back(std::move(newEntry));
1147 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 traceInboundQueueLengthLocked();
1149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001151 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001152 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1153 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 // Optimize app switch latency.
1155 // If the application takes too long to catch up then we drop all events preceding
1156 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001157 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001159 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001161 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001163 if (DEBUG_APP_SWITCH) {
1164 ALOGD("App switch is pending!");
1165 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 mAppSwitchSawKeyDown = false;
1168 needWake = true;
1169 }
1170 }
1171 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001172
1173 // If a new up event comes in, and the pending event with same key code has been asked
1174 // to try again later because of the policy. We have to reset the intercept key wake up
1175 // time for it may have been handled in the policy and could be dropped.
1176 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1177 mPendingEvent->type == EventEntry::Type::KEY) {
1178 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1179 if (pendingKey.keyCode == keyEntry.keyCode &&
1180 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001181 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1182 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001183 pendingKey.interceptKeyWakeupTime = 0;
1184 needWake = true;
1185 }
1186 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187 break;
1188 }
1189
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001190 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001191 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1192 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1194 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001195 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001199 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1201 break;
1202 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001203 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001204 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001205 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001206 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001207 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1208 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001209 // nothing to do
1210 break;
1211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213
1214 return needWake;
1215}
1216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001218 // Do not store sensor event in recent queue to avoid flooding the queue.
1219 if (entry->type != EventEntry::Type::SENSOR) {
1220 mRecentQueue.push_back(entry);
1221 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001222 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001223 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225}
1226
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001227std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001228InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001229 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001231 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001232 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001233 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001234 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001235 continue;
1236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001238 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001239 if (!info.isSpy() &&
1240 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001241 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001242 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001243
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001244 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1245 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001246 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001247 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
1249 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001250 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251}
1252
Prabir Pradhand65552b2021-10-07 11:23:50 -07001253std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001254 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001255 // Traverse windows from front to back and gather the touched spy windows.
1256 std::vector<sp<WindowInfoHandle>> spyWindows;
1257 const auto& windowHandles = getWindowHandlesLocked(displayId);
1258 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1259 const WindowInfo& info = *windowHandle->getInfo();
1260
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001261 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001262 continue;
1263 }
1264 if (!info.isSpy()) {
1265 // The first touched non-spy window was found, so return the spy windows touched so far.
1266 return spyWindows;
1267 }
1268 spyWindows.push_back(windowHandle);
1269 }
1270 return spyWindows;
1271}
1272
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001273void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 const char* reason;
1275 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001276 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001277 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001278 ALOGD("Dropped event because policy consumed it.");
1279 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 reason = "inbound event was dropped because the policy consumed it";
1281 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001282 case DropReason::DISABLED:
1283 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 ALOGI("Dropped event because input dispatch is disabled.");
1285 }
1286 reason = "inbound event was dropped because input dispatch is disabled";
1287 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001288 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 ALOGI("Dropped event because of pending overdue app switch.");
1290 reason = "inbound event was dropped because of pending overdue app switch";
1291 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001292 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 ALOGI("Dropped event because the current application is not responding and the user "
1294 "has started interacting with a different application.");
1295 reason = "inbound event was dropped because the current application is not responding "
1296 "and the user has started interacting with a different application";
1297 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001298 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 ALOGI("Dropped event because it is stale.");
1300 reason = "inbound event was dropped because it is stale";
1301 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001302 case DropReason::NO_POINTER_CAPTURE:
1303 ALOGI("Dropped event because there is no window with Pointer Capture.");
1304 reason = "inbound event was dropped because there is no window with Pointer Capture";
1305 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001306 case DropReason::NOT_DROPPED: {
1307 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
1311
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001312 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001313 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001314 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001318 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1320 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001321 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 synthesizeCancelationEventsForAllConnectionsLocked(options);
1323 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001324 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1325 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001326 synthesizeCancelationEventsForAllConnectionsLocked(options);
1327 }
1328 break;
1329 }
Chris Yef59a2f42020-10-16 12:55:26 -07001330 case EventEntry::Type::SENSOR: {
1331 break;
1332 }
arthurhungb89ccb02020-12-30 16:19:01 +08001333 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1334 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001335 break;
1336 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001337 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001338 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001339 case EventEntry::Type::CONFIGURATION_CHANGED:
1340 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001341 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001342 break;
1343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 }
1345}
1346
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001347static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001348 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1349 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350}
1351
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001352bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1353 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1354 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1355 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356}
1357
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001358bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001359 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360}
1361
1362void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001363 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001365 if (DEBUG_APP_SWITCH) {
1366 if (handled) {
1367 ALOGD("App switch has arrived.");
1368 } else {
1369 ALOGD("App switch was abandoned.");
1370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372}
1373
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001375 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376}
1377
Prabir Pradhancef936d2021-07-21 16:17:52 +00001378bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001379 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 return false;
1381 }
1382
1383 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001384 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001385 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001386 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1387 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001388 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 return true;
1390}
1391
Prabir Pradhancef936d2021-07-21 16:17:52 +00001392void InputDispatcher::postCommandLocked(Command&& command) {
1393 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394}
1395
1396void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001397 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001398 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001399 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 releaseInboundEventLocked(entry);
1401 }
1402 traceInboundQueueLengthLocked();
1403}
1404
1405void InputDispatcher::releasePendingEventLocked() {
1406 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001408 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 }
1410}
1411
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001412void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001414 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001415 if (DEBUG_DISPATCH_CYCLE) {
1416 ALOGD("Injected inbound event was dropped.");
1417 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001421 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 }
1423 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424}
1425
1426void InputDispatcher::resetKeyRepeatLocked() {
1427 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001428 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 }
1430}
1431
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001432std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1433 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434
Michael Wright2e732952014-09-24 13:26:59 -07001435 uint32_t policyFlags = entry->policyFlags &
1436 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438 std::shared_ptr<KeyEntry> newEntry =
1439 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1440 entry->source, entry->displayId, policyFlags, entry->action,
1441 entry->flags, entry->keyCode, entry->scanCode,
1442 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444 newEntry->syntheticRepeat = true;
1445 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001447 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448}
1449
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001452 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1453 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455
1456 // Reset key repeating in case a keyboard device was added or removed or something.
1457 resetKeyRepeatLocked();
1458
1459 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001460 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1461 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001462 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001463 };
1464 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 return true;
1466}
1467
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001468bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1469 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001470 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1471 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1472 entry.deviceId);
1473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474
liushenxiang42232912021-05-21 20:24:09 +08001475 // Reset key repeating in case a keyboard device was disabled or enabled.
1476 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1477 resetKeyRepeatLocked();
1478 }
1479
Michael Wrightfb04fd52022-11-24 22:31:11 +00001480 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001483
1484 // Remove all active pointers from this device
1485 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1486 touchState.removeAllPointersForDevice(entry.deviceId);
1487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 return true;
1489}
1490
Vishnu Nairad321cd2020-08-20 16:40:21 -07001491void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001492 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001493 if (mPendingEvent != nullptr) {
1494 // Move the pending event to the front of the queue. This will give the chance
1495 // for the pending event to get dispatched to the newly focused window
1496 mInboundQueue.push_front(mPendingEvent);
1497 mPendingEvent = nullptr;
1498 }
1499
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001500 std::unique_ptr<FocusEntry> focusEntry =
1501 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1502 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001503
1504 // This event should go to the front of the queue, but behind all other focus events
1505 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001506 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001507 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001508 [](const std::shared_ptr<EventEntry>& event) {
1509 return event->type == EventEntry::Type::FOCUS;
1510 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001511
1512 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001514}
1515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001517 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001518 if (channel == nullptr) {
1519 return; // Window has gone away
1520 }
1521 InputTarget target;
1522 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001523 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001524 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001525 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1526 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001527 std::string reason = std::string("reason=").append(entry->reason);
1528 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001529 dispatchEventLocked(currentTime, entry, {target});
1530}
1531
Prabir Pradhan99987712020-11-10 18:43:05 -08001532void InputDispatcher::dispatchPointerCaptureChangedLocked(
1533 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1534 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001535 dropReason = DropReason::NOT_DROPPED;
1536
Prabir Pradhan99987712020-11-10 18:43:05 -08001537 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001538 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001539
1540 if (entry->pointerCaptureRequest.enable) {
1541 // Enable Pointer Capture.
1542 if (haveWindowWithPointerCapture &&
1543 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001544 // This can happen if pointer capture is disabled and re-enabled before we notify the
1545 // app of the state change, so there is no need to notify the app.
1546 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1547 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001548 }
1549 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001550 // This can happen if a window requests capture and immediately releases capture.
1551 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001552 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001553 return;
1554 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001555 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1556 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1557 return;
1558 }
1559
Vishnu Nairc519ff72021-01-21 08:23:08 -08001560 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001561 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1562 mWindowTokenWithPointerCapture = token;
1563 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001564 // Disable Pointer Capture.
1565 // We do not check if the sequence number matches for requests to disable Pointer Capture
1566 // for two reasons:
1567 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1568 // to disable capture with the same sequence number: one generated by
1569 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1570 // Capture being disabled in InputReader.
1571 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1572 // actual Pointer Capture state that affects events being generated by input devices is
1573 // in InputReader.
1574 if (!haveWindowWithPointerCapture) {
1575 // Pointer capture was already forcefully disabled because of focus change.
1576 dropReason = DropReason::NOT_DROPPED;
1577 return;
1578 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001579 token = mWindowTokenWithPointerCapture;
1580 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001581 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001582 setPointerCaptureLocked(false);
1583 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001584 }
1585
1586 auto channel = getInputChannelLocked(token);
1587 if (channel == nullptr) {
1588 // Window has gone away, clean up Pointer Capture state.
1589 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001590 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001591 setPointerCaptureLocked(false);
1592 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001593 return;
1594 }
1595 InputTarget target;
1596 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001597 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001598 entry->dispatchInProgress = true;
1599 dispatchEventLocked(currentTime, entry, {target});
1600
1601 dropReason = DropReason::NOT_DROPPED;
1602}
1603
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001604void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1605 const std::shared_ptr<TouchModeEntry>& entry) {
1606 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001607 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001608 if (windowHandles.empty()) {
1609 return;
1610 }
1611 const std::vector<InputTarget> inputTargets =
1612 getInputTargetsFromWindowHandlesLocked(windowHandles);
1613 if (inputTargets.empty()) {
1614 return;
1615 }
1616 entry->dispatchInProgress = true;
1617 dispatchEventLocked(currentTime, entry, inputTargets);
1618}
1619
1620std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1621 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1622 std::vector<InputTarget> inputTargets;
1623 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001624 const sp<IBinder>& token = handle->getToken();
1625 if (token == nullptr) {
1626 continue;
1627 }
1628 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1629 if (channel == nullptr) {
1630 continue; // Window has gone away
1631 }
1632 InputTarget target;
1633 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001634 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001635 inputTargets.push_back(target);
1636 }
1637 return inputTargets;
1638}
1639
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001640bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001641 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001643 if (!entry->dispatchInProgress) {
1644 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1645 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1646 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1647 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001648 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 // We have seen two identical key downs in a row which indicates that the device
1650 // driver is automatically generating key repeats itself. We take note of the
1651 // repeat here, but we disable our own next key repeat timer since it is clear that
1652 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001653 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1654 // Make sure we don't get key down from a different device. If a different
1655 // device Id has same key pressed down, the new device Id will replace the
1656 // current one to hold the key repeat with repeat count reset.
1657 // In the future when got a KEY_UP on the device id, drop it and do not
1658 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1660 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001661 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 } else {
1663 // Not a repeat. Save key down state in case we do see a repeat later.
1664 resetKeyRepeatLocked();
1665 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1666 }
1667 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001668 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1669 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001670 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001671 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001672 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1673 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 resetKeyRepeatLocked();
1676 }
1677
1678 if (entry->repeatCount == 1) {
1679 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1680 } else {
1681 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1682 }
1683
1684 entry->dispatchInProgress = true;
1685
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001686 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 }
1688
1689 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001690 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 if (currentTime < entry->interceptKeyWakeupTime) {
1692 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1693 *nextWakeupTime = entry->interceptKeyWakeupTime;
1694 }
1695 return false; // wait until next wakeup
1696 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001697 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 entry->interceptKeyWakeupTime = 0;
1699 }
1700
1701 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001702 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001704 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001705 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001706
1707 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1708 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1709 };
1710 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001711 // Poke user activity for keys not passed to user
1712 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 return false; // wait for the command to run
1714 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001715 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001717 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001718 if (*dropReason == DropReason::NOT_DROPPED) {
1719 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 }
1721 }
1722
1723 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001724 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001725 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001726 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1727 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001728 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001729 // Poke user activity for undispatched keys
1730 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 return true;
1732 }
1733
1734 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001735 InputEventInjectionResult injectionResult;
1736 sp<WindowInfoHandle> focusedWindow =
1737 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1738 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001739 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 return false;
1741 }
1742
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001743 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001744 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 return true;
1746 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001747 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1748
1749 std::vector<InputTarget> inputTargets;
1750 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001751 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001752 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001754 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001755 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756
1757 // Dispatch the key.
1758 dispatchEventLocked(currentTime, entry, inputTargets);
1759 return true;
1760}
1761
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001762void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001763 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1764 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1765 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1766 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1767 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1768 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1769 entry.metaState, entry.repeatCount, entry.downTime);
1770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771}
1772
Prabir Pradhancef936d2021-07-21 16:17:52 +00001773void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1774 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001775 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001776 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1777 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1778 "source=0x%x, sensorType=%s",
1779 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001780 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001781 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001782 auto command = [this, entry]() REQUIRES(mLock) {
1783 scoped_unlock unlock(mLock);
1784
1785 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001786 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001787 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001788 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1789 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001790 };
1791 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001792}
1793
1794bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001795 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1796 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001797 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001798 }
Chris Yef59a2f42020-10-16 12:55:26 -07001799 { // acquire lock
1800 std::scoped_lock _l(mLock);
1801
1802 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1803 std::shared_ptr<EventEntry> entry = *it;
1804 if (entry->type == EventEntry::Type::SENSOR) {
1805 it = mInboundQueue.erase(it);
1806 releaseInboundEventLocked(entry);
1807 }
1808 }
1809 }
1810 return true;
1811}
1812
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001813bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001814 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001815 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001817 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 entry->dispatchInProgress = true;
1819
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001820 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822
1823 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001824 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001825 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001826 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1827 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 return true;
1829 }
1830
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001831 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832
1833 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001834 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835
1836 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 if (isPointerEvent) {
1839 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001840
1841 if (mDragState &&
1842 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1843 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1844 pilferPointersLocked(mDragState->dragWindow->getToken());
1845 }
1846
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001847 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001848 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001849 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001850 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1851 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 } else {
1853 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001854 sp<WindowInfoHandle> focusedWindow =
1855 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1856 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1857 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1858 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001859 InputTarget::Flags::FOREGROUND |
1860 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001861 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001864 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 return false;
1866 }
1867
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001868 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001869 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001870 return true;
1871 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001873 CancelationOptions::Mode mode(
1874 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1875 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001876 CancelationOptions options(mode, "input event injection failed");
1877 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 return true;
1879 }
1880
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001881 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001882 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883
1884 // Dispatch the motion.
1885 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001886 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001887 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 synthesizeCancelationEventsForAllConnectionsLocked(options);
1889 }
1890 dispatchEventLocked(currentTime, entry, inputTargets);
1891 return true;
1892}
1893
chaviw98318de2021-05-19 16:45:23 -05001894void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001895 bool isExiting, const int32_t rawX,
1896 const int32_t rawY) {
1897 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001898 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001899 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1900 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001901
1902 enqueueInboundEventLocked(std::move(dragEntry));
1903}
1904
1905void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1906 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1907 if (channel == nullptr) {
1908 return; // Window has gone away
1909 }
1910 InputTarget target;
1911 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001912 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001913 entry->dispatchInProgress = true;
1914 dispatchEventLocked(currentTime, entry, {target});
1915}
1916
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001917void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001918 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001919 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001920 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001921 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001922 "metaState=0x%x, buttonState=0x%x,"
1923 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001924 prefix, entry.eventTime, entry.deviceId,
1925 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1926 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1927 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1928 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001930 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001931 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001932 "x=%f, y=%f, pressure=%f, size=%f, "
1933 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1934 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001935 i, entry.pointerProperties[i].id,
1936 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001937 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1938 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1939 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1940 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1941 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1942 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1943 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948}
1949
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001950void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1951 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001952 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001954 if (DEBUG_DISPATCH_CYCLE) {
1955 ALOGD("dispatchEventToCurrentInputTargets");
1956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001958 updateInteractionTokensLocked(*eventEntry, inputTargets);
1959
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1961
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001962 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001964 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001965 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001966 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001967 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001968 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001970 if (DEBUG_FOCUS) {
1971 ALOGD("Dropping event delivery to target with channel '%s' because it "
1972 "is no longer registered with the input dispatcher.",
1973 inputTarget.inputChannel->getName().c_str());
1974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
1976 }
1977}
1978
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001979void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001980 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1981 // If the policy decides to close the app, we will get a channel removal event via
1982 // unregisterInputChannel, and will clean up the connection that way. We are already not
1983 // sending new pointers to the connection when it blocked, but focused events will continue to
1984 // pile up.
1985 ALOGW("Canceling events for %s because it is unresponsive",
1986 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001987 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001988 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 "application not responding");
1990 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992}
1993
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001995 if (DEBUG_FOCUS) {
1996 ALOGD("Resetting ANR timeouts.");
1997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
1999 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002000 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002001 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002}
2003
Tiger Huang721e26f2018-07-24 22:26:19 +08002004/**
2005 * Get the display id that the given event should go to. If this event specifies a valid display id,
2006 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2007 * Focused display is the display that the user most recently interacted with.
2008 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002009int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002010 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002011 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002012 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002013 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2014 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002015 break;
2016 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002017 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2019 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002020 break;
2021 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002022 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002023 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002024 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002025 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002026 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002027 case EventEntry::Type::SENSOR:
2028 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002029 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002030 return ADISPLAY_ID_NONE;
2031 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002032 }
2033 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2034}
2035
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002036bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2037 const char* focusedWindowName) {
2038 if (mAnrTracker.empty()) {
2039 // already processed all events that we waited for
2040 mKeyIsWaitingForEventsTimeout = std::nullopt;
2041 return false;
2042 }
2043
2044 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2045 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002046 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002047 mKeyIsWaitingForEventsTimeout = currentTime +
2048 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2049 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 return true;
2051 }
2052
2053 // We still have pending events, and already started the timer
2054 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2055 return true; // Still waiting
2056 }
2057
2058 // Waited too long, and some connection still hasn't processed all motions
2059 // Just send the key to the focused window
2060 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2061 focusedWindowName);
2062 mKeyIsWaitingForEventsTimeout = std::nullopt;
2063 return false;
2064}
2065
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002066sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2067 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2068 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002069 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Tiger Huang721e26f2018-07-24 22:26:19 +08002072 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002073 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002074 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002075 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2076
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 // If there is no currently focused window and no focused application
2078 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002079 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2080 ALOGI("Dropping %s event because there is no focused window or focused application in "
2081 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002082 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002083 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 }
2085
Vishnu Nair062a8672021-09-03 16:07:44 -07002086 // Drop key events if requested by input feature
2087 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002088 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002089 }
2090
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2092 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2093 // start interacting with another application via touch (app switch). This code can be removed
2094 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2095 // an app is expected to have a focused window.
2096 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2097 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2098 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002099 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2100 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2101 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002102 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002103 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 ALOGW("Waiting because no window has focus but %s may eventually add a "
2105 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002106 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002108 outInjectionResult = InputEventInjectionResult::PENDING;
2109 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2111 // Already raised ANR. Drop the event
2112 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002113 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002114 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 } else {
2116 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002117 outInjectionResult = InputEventInjectionResult::PENDING;
2118 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 }
2120 }
2121
2122 // we have a valid, non-null focused window
2123 resetNoFocusedWindowTimeoutLocked();
2124
Prabir Pradhan5735a322022-04-11 17:23:34 +00002125 // Verify targeted injection.
2126 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2127 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002128 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2129 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 }
2131
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002132 if (focusedWindowHandle->getInfo()->inputConfig.test(
2133 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002134 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135 outInjectionResult = InputEventInjectionResult::PENDING;
2136 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002137 }
2138
2139 // If the event is a key event, then we must wait for all previous events to
2140 // complete before delivering it because previous events may have the
2141 // side-effect of transferring focus to a different window and we want to
2142 // ensure that the following keys are sent to the new window.
2143 //
2144 // Suppose the user touches a button in a window then immediately presses "A".
2145 // If the button causes a pop-up window to appear then we want to ensure that
2146 // the "A" key is delivered to the new pop-up window. This is because users
2147 // often anticipate pending UI changes when typing on a keyboard.
2148 // To obtain this behavior, we must serialize key events with respect to all
2149 // prior input events.
2150 if (entry.type == EventEntry::Type::KEY) {
2151 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2152 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002153 outInjectionResult = InputEventInjectionResult::PENDING;
2154 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2159 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160}
2161
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162/**
2163 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2164 * that are currently unresponsive.
2165 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002166std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2167 const std::vector<Monitor>& monitors) const {
2168 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002170 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002171 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002172 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 if (connection == nullptr) {
2174 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002175 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 return false;
2177 }
2178 if (!connection->responsive) {
2179 ALOGW("Unresponsive monitor %s will not get the new gesture",
2180 connection->inputChannel->getName().c_str());
2181 return false;
2182 }
2183 return true;
2184 });
2185 return responsiveMonitors;
2186}
2187
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002188/**
2189 * In general, touch should be always split between windows. Some exceptions:
2190 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2191 * from the same device, *and* the window that's receiving the current pointer does not support
2192 * split touch.
2193 * 2. Don't split mouse events
2194 */
2195bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2196 const MotionEntry& entry) const {
2197 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2198 // We should never split mouse events
2199 return false;
2200 }
2201 for (const TouchedWindow& touchedWindow : touchState.windows) {
2202 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2203 // Spy windows should not affect whether or not touch is split.
2204 continue;
2205 }
2206 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2207 continue;
2208 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002209 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2210 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2211 // Wallpaper window should not affect whether or not touch is split
2212 continue;
2213 }
2214
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002215 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2216 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002217 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002218 return false;
2219 }
2220 }
2221 return true;
2222}
2223
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002224std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002225 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2226 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002227 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002229 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 // For security reasons, we defer updating the touch state until we are sure that
2231 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002232 const int32_t displayId = entry.displayId;
2233 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002234 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235
2236 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002237 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002239 // Copy current touch state into tempTouchState.
2240 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2241 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002242 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002243 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2245 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002246 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002247 }
2248
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002249 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002250 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002251 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002252
2253 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2254 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2255 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002256 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2257 // touchable windows.
2258 const bool wasDown = oldState != nullptr && oldState->isDown();
2259 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2260 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002261 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2262 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2263 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002264 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002265
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002266 // If pointers are already down, let's finish the current gesture and ignore the new events
2267 // from another device. However, if the new event is a down event, let's cancel the current
2268 // touch and let the new one take over.
2269 if (switchedDevice && wasDown && !isDown) {
2270 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2271 << " is already down in display " << displayId << ": " << entry.getDescription();
2272 // TODO(b/211379801): test multiple simultaneous input streams.
2273 outInjectionResult = InputEventInjectionResult::FAILED;
2274 return {}; // wrong device
2275 }
2276
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002278 // If a new gesture is starting, clear the touch state completely.
2279 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.deviceId = entry.deviceId;
2281 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002283 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002284 ALOGI("Dropping move event because a pointer for a different device is already active "
2285 "in display %" PRId32,
2286 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002287 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002288 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002289 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002292 if (isHoverAction) {
2293 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2294 // all of the existing hovering pointers and recompute.
2295 tempTouchState.clearHoveringPointers();
2296 }
2297
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2299 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002300 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002301 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002302 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2303 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002304 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002305 auto [newTouchedWindowHandle, outsideTargets] =
2306 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002307
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002308 if (isDown) {
2309 targets += outsideTargets;
2310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002312 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002313 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002315 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002316 }
2317
Prabir Pradhan5735a322022-04-11 17:23:34 +00002318 // Verify targeted injection.
2319 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2320 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002321 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002322 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002323 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002324 }
2325
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002326 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002327 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002328 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2329 // New window supports splitting, but we should never split mouse events.
2330 isSplit = !isFromMouse;
2331 } else if (isSplit) {
2332 // New window does not support splitting but we have already split events.
2333 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002334 newTouchedWindowHandle = nullptr;
2335 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002336 } else {
2337 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002338 // be delivered to a new window which supports split touch. Pointers from a mouse device
2339 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002340 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002341 }
2342
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002343 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002344 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002345 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002346 // Process the foreground window first so that it is the first to receive the event.
2347 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002348 }
2349
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002351 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2352 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002353 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002354 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002355 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002356 }
2357
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002358 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002359 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002360 continue;
2361 }
2362
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002363 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2364 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002365 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002366 // The "windowHandle" is the target of this hovering pointer.
2367 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002368 }
2369
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002370 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002371 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002372
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002373 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2374 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002375 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002376 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002377
2378 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002379 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380 }
2381 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002382 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002384 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002386
2387 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002388 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002389 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002390 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002391 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002393 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2394 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2395
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002396 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2397 // still add a window to the touch state. We should avoid doing that, but some of the
2398 // later checks ("at least one foreground window") rely on this in order to dispatch
2399 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002400 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002401 isDownOrPointerDown
2402 ? std::make_optional(entry.eventTime)
2403 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002404
2405 // If this is the pointer going down and the touched window has a wallpaper
2406 // then also add the touched wallpaper windows so they are locked in for the duration
2407 // of the touch gesture.
2408 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2409 // engine only supports touch events. We would need to add a mechanism similar
2410 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002411 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002412 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2413 windowHandle->getInfo()->inputConfig.test(
2414 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2415 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2416 if (wallpaper != nullptr) {
2417 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2418 InputTarget::Flags::WINDOW_IS_OBSCURED |
2419 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2420 InputTarget::Flags::DISPATCH_AS_IS;
2421 if (isSplit) {
2422 wallpaperFlags |= InputTarget::Flags::SPLIT;
2423 }
2424 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2425 entry.eventTime);
2426 }
2427 }
2428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002430
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002431 // If a window is already pilfering some pointers, give it this new pointer as well and
2432 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2433 // which is a specific behaviour that we want.
2434 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2435 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002436 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002437 touchedWindow.pilferedPointerIds.count() > 0) {
2438 // This window is already pilfering some pointers, and this new pointer is also
2439 // going to it. Therefore, take over this pointer and don't give it to anyone
2440 // else.
2441 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002442 }
2443 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002444
2445 // Restrict all pilfered pointers to the pilfering windows.
2446 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 } else {
2448 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2449
2450 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002451 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002452 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2453 "dropped the pointer down event in display "
2454 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002455 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002456 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
2458
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002459 // If the pointer is not currently hovering, then ignore the event.
2460 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2461 const int32_t pointerId = entry.pointerProperties[0].id;
2462 if (oldState == nullptr ||
2463 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2464 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2465 "display "
2466 << displayId << ": " << entry.getDescription();
2467 outInjectionResult = InputEventInjectionResult::FAILED;
2468 return {};
2469 }
2470 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2471 }
2472
arthurhung6d4bed92021-03-17 11:59:33 +08002473 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002474
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002476 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002477 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002478 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002479 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002480 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002481 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002482 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002483 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002484
Prabir Pradhan5735a322022-04-11 17:23:34 +00002485 // Verify targeted injection.
2486 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2487 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002488 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002489 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002490 }
2491
Vishnu Nair062a8672021-09-03 16:07:44 -07002492 // Drop touch events if requested by input feature
2493 if (newTouchedWindowHandle != nullptr &&
2494 shouldDropInput(entry, newTouchedWindowHandle)) {
2495 newTouchedWindowHandle = nullptr;
2496 }
2497
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002498 if (newTouchedWindowHandle != nullptr &&
2499 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002500 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2501 oldTouchedWindowHandle->getName().c_str(),
2502 newTouchedWindowHandle->getName().c_str(), displayId);
2503
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002505 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002506 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002507 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002508
2509 const TouchedWindow& touchedWindow =
2510 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2511 addWindowTargetLocked(oldTouchedWindowHandle,
2512 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2513 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514
2515 // Make a slippery entrance into the new window.
2516 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002517 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 }
2519
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002520 ftl::Flags<InputTarget::Flags> targetFlags =
2521 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002522 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002523 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002526 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 }
2528 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002529 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002530 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002531 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 }
2533
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002534 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2535 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002536
2537 // Check if the wallpaper window should deliver the corresponding event.
2538 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002539 tempTouchState, pointerId, targets);
2540 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542 }
Arthur Hung96483742022-11-15 03:30:48 +00002543
2544 // Update the pointerIds for non-splittable when it received pointer down.
2545 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2546 // If no split, we suppose all touched windows should receive pointer down.
2547 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2548 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2549 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2550 // Ignore drag window for it should just track one pointer.
2551 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2552 continue;
2553 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002554 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002555 }
2556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002559 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002560 {
2561 std::vector<TouchedWindow> hoveringWindows =
2562 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2563 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2564 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2565 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2566 targets);
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569
Prabir Pradhan5735a322022-04-11 17:23:34 +00002570 // Ensure that all touched windows are valid for injection.
2571 if (entry.injectionState != nullptr) {
2572 std::string errs;
2573 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002574 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002575 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2576 // dispatched to any uid, since the coords will be zeroed out later.
2577 continue;
2578 }
2579 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2580 if (err) errs += "\n - " + *err;
2581 }
2582 if (!errs.empty()) {
2583 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2584 "%d:%s",
2585 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002586 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002587 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002588 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002589 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002590
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002591 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2592 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002594 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002595 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002596 if (foregroundWindowHandle) {
2597 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002598 for (InputTarget& target : targets) {
2599 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2600 sp<WindowInfoHandle> targetWindow =
2601 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2602 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2603 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 }
2606 }
2607 }
2608 }
2609
Harry Cuttsb166c002023-05-09 13:06:05 +00002610 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2611 // only want the system UI to handle these gestures.
2612 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2613 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2614 if (isTouchpadNavGesture) {
2615 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2616 }
2617
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002618 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002619 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002620 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002621 // Windows with hovering pointers are getting persisted inside TouchState.
2622 // Do not send this event to those windows.
2623 continue;
2624 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002625
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002626 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2627 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2628 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002629 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002630
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002631 if (targets.empty()) {
2632 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2633 outInjectionResult = InputEventInjectionResult::FAILED;
2634 return {};
2635 }
2636
2637 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2638 // window that is actually receiving the entire gesture.
2639 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2640 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2641 })) {
2642 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2643 << entry.getDescription();
2644 outInjectionResult = InputEventInjectionResult::FAILED;
2645 return {};
2646 }
2647
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002648 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002649 // Drop the outside or hover touch windows since we will not care about them
2650 // in the next iteration.
2651 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002654 if (switchedDevice) {
2655 if (DEBUG_FOCUS) {
2656 ALOGD("Conflicting pointer actions: Switched to a different device.");
2657 }
2658 *outConflictingPointerActions = true;
2659 }
2660
2661 if (isHoverAction) {
2662 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002663 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002664 ALOGD_IF(DEBUG_FOCUS,
2665 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002666 *outConflictingPointerActions = true;
2667 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002668 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2669 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2670 tempTouchState.deviceId = entry.deviceId;
2671 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002672 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002673 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2674 // Pointer went up.
2675 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002676 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002677 // All pointers up or canceled.
2678 tempTouchState.reset();
2679 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2680 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002681 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2682 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002683 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002684 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002685 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2686 // One pointer went up.
2687 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2688 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002690 for (size_t i = 0; i < tempTouchState.windows.size();) {
2691 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002692 touchedWindow.pointerIds.reset(pointerId);
2693 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002694 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2695 continue;
2696 }
2697 i += 1;
2698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 }
2700
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002701 // Save changes unless the action was scroll in which case the temporary touch
2702 // state was only valid for this one action.
2703 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002704 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002705 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002706 mTouchStatesByDisplay[displayId] = tempTouchState;
2707 } else {
2708 mTouchStatesByDisplay.erase(displayId);
2709 }
2710 }
2711
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002712 if (tempTouchState.windows.empty()) {
2713 mTouchStatesByDisplay.erase(displayId);
2714 }
2715
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002716 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717}
2718
arthurhung6d4bed92021-03-17 11:59:33 +08002719void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002720 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2721 // have an explicit reason to support it.
2722 constexpr bool isStylus = false;
2723
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002724 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002725 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002726 if (dropWindow) {
2727 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002728 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002729 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002730 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002731 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002732 }
2733 mDragState.reset();
2734}
2735
2736void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002737 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002738 return;
2739 }
2740
arthurhung6d4bed92021-03-17 11:59:33 +08002741 if (!mDragState->isStartDrag) {
2742 mDragState->isStartDrag = true;
2743 mDragState->isStylusButtonDownAtStart =
2744 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2745 }
2746
Arthur Hung54745652022-04-20 07:17:41 +00002747 // Find the pointer index by id.
2748 int32_t pointerIndex = 0;
2749 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2750 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2751 if (pointerProperties.id == mDragState->pointerId) {
2752 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002753 }
Arthur Hung54745652022-04-20 07:17:41 +00002754 }
arthurhung6d4bed92021-03-17 11:59:33 +08002755
Arthur Hung54745652022-04-20 07:17:41 +00002756 if (uint32_t(pointerIndex) == entry.pointerCount) {
2757 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002758 }
2759
2760 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2761 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2762 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2763
2764 switch (maskedAction) {
2765 case AMOTION_EVENT_ACTION_MOVE: {
2766 // Handle the special case : stylus button no longer pressed.
2767 bool isStylusButtonDown =
2768 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2769 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2770 finishDragAndDrop(entry.displayId, x, y);
2771 return;
2772 }
2773
2774 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2775 // until we have an explicit reason to support it.
2776 constexpr bool isStylus = false;
2777
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002778 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002779 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002780 // enqueue drag exit if needed.
2781 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2782 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2783 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002784 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002785 y);
2786 }
2787 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2788 }
2789 // enqueue drag location if needed.
2790 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002791 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002792 }
2793 break;
2794 }
2795
2796 case AMOTION_EVENT_ACTION_POINTER_UP:
2797 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2798 break;
2799 }
2800 // The drag pointer is up.
2801 [[fallthrough]];
2802 case AMOTION_EVENT_ACTION_UP:
2803 finishDragAndDrop(entry.displayId, x, y);
2804 break;
2805 case AMOTION_EVENT_ACTION_CANCEL: {
2806 ALOGD("Receiving cancel when drag and drop.");
2807 sendDropWindowCommandLocked(nullptr, 0, 0);
2808 mDragState.reset();
2809 break;
2810 }
arthurhungb89ccb02020-12-30 16:19:01 +08002811 }
2812}
2813
chaviw98318de2021-05-19 16:45:23 -05002814void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002815 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002816 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002817 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002818 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002819 std::vector<InputTarget>::iterator it =
2820 std::find_if(inputTargets.begin(), inputTargets.end(),
2821 [&windowHandle](const InputTarget& inputTarget) {
2822 return inputTarget.inputChannel->getConnectionToken() ==
2823 windowHandle->getToken();
2824 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002825
chaviw98318de2021-05-19 16:45:23 -05002826 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002827
2828 if (it == inputTargets.end()) {
2829 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002830 std::shared_ptr<InputChannel> inputChannel =
2831 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002832 if (inputChannel == nullptr) {
2833 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2834 return;
2835 }
2836 inputTarget.inputChannel = inputChannel;
2837 inputTarget.flags = targetFlags;
2838 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002839 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002840 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2841 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002842 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002843 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002844 // DisplayInfo not found for this window on display windowInfo->displayId.
2845 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002846 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002847 inputTargets.push_back(inputTarget);
2848 it = inputTargets.end() - 1;
2849 }
2850
2851 ALOG_ASSERT(it->flags == targetFlags);
2852 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2853
chaviw1ff3d1e2020-07-01 15:53:47 -07002854 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855}
2856
Michael Wright3dd60e22019-03-27 22:06:44 +00002857void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002858 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002859 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2860 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002861
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002862 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2863 InputTarget target;
2864 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002865 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002866 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2867 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002868 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2869 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002870 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002871 target.setDefaultPointerTransform(target.displayTransform);
2872 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
2874}
2875
Robert Carrc9bf1d32020-04-13 17:21:08 -07002876/**
2877 * Indicate whether one window handle should be considered as obscuring
2878 * another window handle. We only check a few preconditions. Actually
2879 * checking the bounds is left to the caller.
2880 */
chaviw98318de2021-05-19 16:45:23 -05002881static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2882 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002883 // Compare by token so cloned layers aren't counted
2884 if (haveSameToken(windowHandle, otherHandle)) {
2885 return false;
2886 }
2887 auto info = windowHandle->getInfo();
2888 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002889 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002890 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002891 } else if (otherInfo->alpha == 0 &&
2892 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002893 // Those act as if they were invisible, so we don't need to flag them.
2894 // We do want to potentially flag touchable windows even if they have 0
2895 // opacity, since they can consume touches and alter the effects of the
2896 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002897 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002898 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2899 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002900 } else if (info->ownerUid == otherInfo->ownerUid) {
2901 // If ownerUid is the same we don't generate occlusion events as there
2902 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002903 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002904 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002905 return false;
2906 } else if (otherInfo->displayId != info->displayId) {
2907 return false;
2908 }
2909 return true;
2910}
2911
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002912/**
2913 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2914 * untrusted, one should check:
2915 *
2916 * 1. If result.hasBlockingOcclusion is true.
2917 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2918 * BLOCK_UNTRUSTED.
2919 *
2920 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2921 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2922 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2923 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2924 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2925 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2926 *
2927 * If neither of those is true, then it means the touch can be allowed.
2928 */
2929InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002930 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2931 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002932 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002933 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002934 TouchOcclusionInfo info;
2935 info.hasBlockingOcclusion = false;
2936 info.obscuringOpacity = 0;
2937 info.obscuringUid = -1;
2938 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002939 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002940 if (windowHandle == otherHandle) {
2941 break; // All future windows are below us. Exit early.
2942 }
chaviw98318de2021-05-19 16:45:23 -05002943 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002944 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2945 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002946 if (DEBUG_TOUCH_OCCLUSION) {
2947 info.debugInfo.push_back(
2948 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2949 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002950 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2951 // we perform the checks below to see if the touch can be propagated or not based on the
2952 // window's touch occlusion mode
2953 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2954 info.hasBlockingOcclusion = true;
2955 info.obscuringUid = otherInfo->ownerUid;
2956 info.obscuringPackage = otherInfo->packageName;
2957 break;
2958 }
2959 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2960 uint32_t uid = otherInfo->ownerUid;
2961 float opacity =
2962 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2963 // Given windows A and B:
2964 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2965 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2966 opacityByUid[uid] = opacity;
2967 if (opacity > info.obscuringOpacity) {
2968 info.obscuringOpacity = opacity;
2969 info.obscuringUid = uid;
2970 info.obscuringPackage = otherInfo->packageName;
2971 }
2972 }
2973 }
2974 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002975 if (DEBUG_TOUCH_OCCLUSION) {
2976 info.debugInfo.push_back(
2977 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2978 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002979 return info;
2980}
2981
chaviw98318de2021-05-19 16:45:23 -05002982std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002983 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002984 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2985 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2986 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2987 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002988 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2989 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2990 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2991 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2992 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002993 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002994 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002995}
2996
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002997bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2998 if (occlusionInfo.hasBlockingOcclusion) {
2999 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
3000 occlusionInfo.obscuringUid);
3001 return false;
3002 }
3003 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
3004 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
3005 "%.2f, maximum allowed = %.2f)",
3006 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
3007 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3008 return false;
3009 }
3010 return true;
3011}
3012
chaviw98318de2021-05-19 16:45:23 -05003013bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003016 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3017 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003018 if (windowHandle == otherHandle) {
3019 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 }
chaviw98318de2021-05-19 16:45:23 -05003021 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003022 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003023 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 return true;
3025 }
3026 }
3027 return false;
3028}
3029
chaviw98318de2021-05-19 16:45:23 -05003030bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003031 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003032 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3033 const WindowInfo* windowInfo = windowHandle->getInfo();
3034 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003035 if (windowHandle == otherHandle) {
3036 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003037 }
chaviw98318de2021-05-19 16:45:23 -05003038 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003039 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003040 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003041 return true;
3042 }
3043 }
3044 return false;
3045}
3046
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003047std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003048 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003049 if (applicationHandle != nullptr) {
3050 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003051 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 } else {
3053 return applicationHandle->getName();
3054 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003055 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003056 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003058 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 }
3060}
3061
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003062void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003063 if (!isUserActivityEvent(eventEntry)) {
3064 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003065 return;
3066 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003067 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003068 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003069 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003070 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003071 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003072 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003073 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 }
3075 }
3076
3077 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003078 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003079 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003080 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3081 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 return;
3083 }
Josep del Riob3981622023-04-18 15:49:45 +00003084 if (windowDisablingUserActivityInfo != nullptr) {
3085 if (DEBUG_DISPATCH_CYCLE) {
3086 ALOGD("Not poking user activity: disabled by window '%s'.",
3087 windowDisablingUserActivityInfo->name.c_str());
3088 }
3089 return;
3090 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003091 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 eventType = USER_ACTIVITY_EVENT_TOUCH;
3093 }
3094 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003096 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003097 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3098 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 return;
3100 }
Josep del Riob3981622023-04-18 15:49:45 +00003101 // If the key code is unknown, we don't consider it user activity
3102 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3103 return;
3104 }
3105 // Don't inhibit events that were intercepted or are not passed to
3106 // the apps, like system shortcuts
3107 if (windowDisablingUserActivityInfo != nullptr &&
3108 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3109 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3110 if (DEBUG_DISPATCH_CYCLE) {
3111 ALOGD("Not poking user activity: disabled by window '%s'.",
3112 windowDisablingUserActivityInfo->name.c_str());
3113 }
3114 return;
3115 }
3116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 eventType = USER_ACTIVITY_EVENT_BUTTON;
3118 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003120 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003121 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003122 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003123 break;
3124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 }
3126
Prabir Pradhancef936d2021-07-21 16:17:52 +00003127 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3128 REQUIRES(mLock) {
3129 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003130 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003131 };
3132 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133}
3134
3135void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003136 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003137 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003138 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003139 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003141 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003142 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003143 ATRACE_NAME(message.c_str());
3144 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003145 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003146 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003147 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003148 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003149 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003150 inputTarget.getPointerInfoString().c_str());
3151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152
3153 // Skip this event if the connection status is not normal.
3154 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003155 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003156 if (DEBUG_DISPATCH_CYCLE) {
3157 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003158 connection->getInputChannelName().c_str(),
3159 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 return;
3162 }
3163
3164 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003165 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003166 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003167 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003168 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003170 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003171 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003172 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3173 logDispatchStateLocked();
3174 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3175 "target on connection "
3176 << connection->getInputChannelName() << " for "
3177 << originalMotionEntry.getDescription();
3178 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003179 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003180 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3181 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 if (!splitMotionEntry) {
3183 return; // split event was dropped
3184 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003185 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3186 std::string reason = std::string("reason=pointer cancel on split window");
3187 android_log_event_list(LOGTAG_INPUT_CANCEL)
3188 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3189 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003190 if (DEBUG_FOCUS) {
3191 ALOGD("channel '%s' ~ Split motion event.",
3192 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003193 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003194 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003195 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3196 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 return;
3198 }
3199 }
3200
3201 // Not splitting. Enqueue dispatch entries for the event as is.
3202 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3203}
3204
3205void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003206 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003207 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003208 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003209 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003211 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003212 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003213 ATRACE_NAME(message.c_str());
3214 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003215 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3216 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003217
hongzuo liu95785e22022-09-06 02:51:35 +00003218 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219
3220 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003221 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003223 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003224 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003225 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003226 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003227 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003228 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003229 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003230 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003231 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003232 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233
3234 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003235 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 startDispatchCycleLocked(currentTime, connection);
3237 }
3238}
3239
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003240void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003242 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003243 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003244 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003245 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3246 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003247 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003248 ATRACE_NAME(message.c_str());
3249 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003250 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3251 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 return;
3253 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003254
3255 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3256 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
3258 // This is a new event.
3259 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003260 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003261 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003263 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3264 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003265 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003267 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003268 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003269 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003270 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003271 dispatchEntry->resolvedAction = keyEntry.action;
3272 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3275 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003276 if (DEBUG_DISPATCH_CYCLE) {
3277 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3278 "event",
3279 connection->getInputChannelName().c_str());
3280 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003281 return; // skip the inconsistent event
3282 }
3283 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003286 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003287 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003288 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3289 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3290 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3291 static_cast<int32_t>(IdGenerator::Source::OTHER);
3292 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003295 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003299 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003301 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3303 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003304 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003305 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 }
3307 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003308 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3309 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003310 if (DEBUG_DISPATCH_CYCLE) {
3311 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3312 "enter event",
3313 connection->getInputChannelName().c_str());
3314 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003315 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3316 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003320 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003321 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3322 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3323 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003324 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3326 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003327 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3332 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003333 if (DEBUG_DISPATCH_CYCLE) {
3334 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3335 "event",
3336 connection->getInputChannelName().c_str());
3337 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 return; // skip the inconsistent event
3339 }
3340
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003341 dispatchEntry->resolvedEventId =
3342 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3343 ? mIdGenerator.nextId()
3344 : motionEntry.id;
3345 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3346 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3347 ") to MotionEvent(id=0x%" PRIx32 ").",
3348 motionEntry.id, dispatchEntry->resolvedEventId);
3349 ATRACE_NAME(message.c_str());
3350 }
3351
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003352 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3353 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3354 // Skip reporting pointer down outside focus to the policy.
3355 break;
3356 }
3357
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003358 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003359 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360
3361 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003363 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003364 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003365 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3366 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003367 break;
3368 }
Chris Yef59a2f42020-10-16 12:55:26 -07003369 case EventEntry::Type::SENSOR: {
3370 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3371 break;
3372 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003373 case EventEntry::Type::CONFIGURATION_CHANGED:
3374 case EventEntry::Type::DEVICE_RESET: {
3375 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003376 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003377 break;
3378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
3380
3381 // Remember that we are waiting for this dispatch to complete.
3382 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003383 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
3385
3386 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003387 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003388 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003389}
3390
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003391/**
3392 * This function is purely for debugging. It helps us understand where the user interaction
3393 * was taking place. For example, if user is touching launcher, we will see a log that user
3394 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3395 * We will see both launcher and wallpaper in that list.
3396 * Once the interaction with a particular set of connections starts, no new logs will be printed
3397 * until the set of interacted connections changes.
3398 *
3399 * The following items are skipped, to reduce the logspam:
3400 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3401 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3402 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3403 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3404 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003405 */
3406void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3407 const std::vector<InputTarget>& targets) {
3408 // Skip ACTION_UP events, and all events other than keys and motions
3409 if (entry.type == EventEntry::Type::KEY) {
3410 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3411 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3412 return;
3413 }
3414 } else if (entry.type == EventEntry::Type::MOTION) {
3415 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3416 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3417 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3418 return;
3419 }
3420 } else {
3421 return; // Not a key or a motion
3422 }
3423
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003424 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003425 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003426 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003427 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003428 continue; // Skip windows that receive ACTION_OUTSIDE
3429 }
3430
3431 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003432 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003433 if (connection == nullptr) {
3434 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003435 }
3436 newConnectionTokens.insert(std::move(token));
3437 newConnections.emplace_back(connection);
3438 }
3439 if (newConnectionTokens == mInteractionConnectionTokens) {
3440 return; // no change
3441 }
3442 mInteractionConnectionTokens = newConnectionTokens;
3443
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003444 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003445 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003446 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003447 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003448 std::string message = "Interaction with: " + targetList;
3449 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003450 message += "<none>";
3451 }
3452 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3453}
3454
chaviwfd6d3512019-03-25 13:23:49 -07003455void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003456 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003457 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003458 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3459 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003460 return;
3461 }
3462
Vishnu Nairc519ff72021-01-21 08:23:08 -08003463 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003464 if (focusedToken == token) {
3465 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003466 return;
3467 }
3468
Prabir Pradhancef936d2021-07-21 16:17:52 +00003469 auto command = [this, token]() REQUIRES(mLock) {
3470 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003471 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003472 };
3473 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474}
3475
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003476status_t InputDispatcher::publishMotionEvent(Connection& connection,
3477 DispatchEntry& dispatchEntry) const {
3478 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3479 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3480
3481 PointerCoords scaledCoords[MAX_POINTERS];
3482 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3483
3484 // Set the X and Y offset and X and Y scale depending on the input source.
3485 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003486 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003487 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3488 if (globalScaleFactor != 1.0f) {
3489 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3490 scaledCoords[i] = motionEntry.pointerCoords[i];
3491 // Don't apply window scale here since we don't want scale to affect raw
3492 // coordinates. The scale will be sent back to the client and applied
3493 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003494 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003495 }
3496 usingCoords = scaledCoords;
3497 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003498 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003499 // We don't want the dispatch target to know the coordinates
3500 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3501 scaledCoords[i].clear();
3502 }
3503 usingCoords = scaledCoords;
3504 }
3505
3506 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3507
3508 // Publish the motion event.
3509 return connection.inputPublisher
3510 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3511 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3512 std::move(hmac), dispatchEntry.resolvedAction,
3513 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3514 motionEntry.edgeFlags, motionEntry.metaState,
3515 motionEntry.buttonState, motionEntry.classification,
3516 dispatchEntry.transform, motionEntry.xPrecision,
3517 motionEntry.yPrecision, motionEntry.xCursorPosition,
3518 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3519 motionEntry.downTime, motionEntry.eventTime,
3520 motionEntry.pointerCount, motionEntry.pointerProperties,
3521 usingCoords);
3522}
3523
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003525 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003526 if (ATRACE_ENABLED()) {
3527 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003528 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003529 ATRACE_NAME(message.c_str());
3530 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003531 if (DEBUG_DISPATCH_CYCLE) {
3532 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003535 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003536 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003538 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003539 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540
3541 // Publish the event.
3542 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003543 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3544 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003545 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003546 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3547 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003548 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3549 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3550 << connection->getInputChannelName();
3551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003553 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003554 status = connection->inputPublisher
3555 .publishKeyEvent(dispatchEntry->seq,
3556 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3557 keyEntry.source, keyEntry.displayId,
3558 std::move(hmac), dispatchEntry->resolvedAction,
3559 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3560 keyEntry.scanCode, keyEntry.metaState,
3561 keyEntry.repeatCount, keyEntry.downTime,
3562 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 }
3565
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003566 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003567 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3568 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3569 << connection->getInputChannelName();
3570 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003571 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572 break;
3573 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003574
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003575 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003576 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003577 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003579 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003580 break;
3581 }
3582
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003583 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3584 const TouchModeEntry& touchModeEntry =
3585 static_cast<const TouchModeEntry&>(eventEntry);
3586 status = connection->inputPublisher
3587 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3588 touchModeEntry.inTouchMode);
3589
3590 break;
3591 }
3592
Prabir Pradhan99987712020-11-10 18:43:05 -08003593 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3594 const auto& captureEntry =
3595 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3596 status = connection->inputPublisher
3597 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003598 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003599 break;
3600 }
3601
arthurhungb89ccb02020-12-30 16:19:01 +08003602 case EventEntry::Type::DRAG: {
3603 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3604 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3605 dragEntry.id, dragEntry.x,
3606 dragEntry.y,
3607 dragEntry.isExiting);
3608 break;
3609 }
3610
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003611 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003612 case EventEntry::Type::DEVICE_RESET:
3613 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003614 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003615 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003616 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
3620 // Check the result.
3621 if (status) {
3622 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003623 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003625 "This is unexpected because the wait queue is empty, so the pipe "
3626 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003627 "event to it, status=%s(%d)",
3628 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3629 status);
Harry Cutts33476232023-01-30 19:57:29 +00003630 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 } else {
3632 // Pipe is full and we are waiting for the app to finish process some events
3633 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003634 if (DEBUG_DISPATCH_CYCLE) {
3635 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3636 "waiting for the application to catch up",
3637 connection->getInputChannelName().c_str());
3638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
3640 } else {
3641 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003642 "status=%s(%d)",
3643 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3644 status);
Harry Cutts33476232023-01-30 19:57:29 +00003645 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647 return;
3648 }
3649
3650 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003651 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3652 connection->outboundQueue.end(),
3653 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003654 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003655 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003656 if (connection->responsive) {
3657 mAnrTracker.insert(dispatchEntry->timeoutTime,
3658 connection->inputChannel->getConnectionToken());
3659 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003660 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662}
3663
chaviw09c8d2d2020-08-24 15:48:26 -07003664std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3665 size_t size;
3666 switch (event.type) {
3667 case VerifiedInputEvent::Type::KEY: {
3668 size = sizeof(VerifiedKeyEvent);
3669 break;
3670 }
3671 case VerifiedInputEvent::Type::MOTION: {
3672 size = sizeof(VerifiedMotionEvent);
3673 break;
3674 }
3675 }
3676 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3677 return mHmacKeyManager.sign(start, size);
3678}
3679
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003680const std::array<uint8_t, 32> InputDispatcher::getSignature(
3681 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003682 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003683 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003684 // Only sign events up and down events as the purely move events
3685 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003686 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003687 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003688
3689 VerifiedMotionEvent verifiedEvent =
3690 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3691 verifiedEvent.actionMasked = actionMasked;
3692 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3693 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003694}
3695
3696const std::array<uint8_t, 32> InputDispatcher::getSignature(
3697 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3698 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3699 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3700 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003701 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003702}
3703
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003705 const std::shared_ptr<Connection>& connection,
3706 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003707 if (DEBUG_DISPATCH_CYCLE) {
3708 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3709 connection->getInputChannelName().c_str(), seq, toString(handled));
3710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003712 if (connection->status == Connection::Status::BROKEN ||
3713 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 return;
3715 }
3716
3717 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003718 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3719 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3720 };
3721 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722}
3723
3724void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003725 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003726 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003727 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003728 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3729 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731
3732 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003733 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003734 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003735 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003736 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737
3738 // The connection appears to be unrecoverably broken.
3739 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003740 if (connection->status == Connection::Status::NORMAL) {
3741 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742
3743 if (notify) {
3744 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003745 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3746 connection->getInputChannelName().c_str());
3747
3748 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003749 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003750 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003751 };
3752 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
3754 }
3755}
3756
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003757void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3758 while (!queue.empty()) {
3759 DispatchEntry* dispatchEntry = queue.front();
3760 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003761 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 }
3763}
3764
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003765void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003767 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 }
3769 delete dispatchEntry;
3770}
3771
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003772int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3773 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003774 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003775 if (connection == nullptr) {
3776 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3777 connectionToken.get(), events);
3778 return 0; // remove the callback
3779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003781 bool notify;
3782 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3783 if (!(events & ALOOPER_EVENT_INPUT)) {
3784 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3785 "events=0x%x",
3786 connection->getInputChannelName().c_str(), events);
3787 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
3789
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003790 nsecs_t currentTime = now();
3791 bool gotOne = false;
3792 status_t status = OK;
3793 for (;;) {
3794 Result<InputPublisher::ConsumerResponse> result =
3795 connection->inputPublisher.receiveConsumerResponse();
3796 if (!result.ok()) {
3797 status = result.error().code();
3798 break;
3799 }
3800
3801 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3802 const InputPublisher::Finished& finish =
3803 std::get<InputPublisher::Finished>(*result);
3804 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3805 finish.consumeTime);
3806 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003807 if (shouldReportMetricsForConnection(*connection)) {
3808 const InputPublisher::Timeline& timeline =
3809 std::get<InputPublisher::Timeline>(*result);
3810 mLatencyTracker
3811 .trackGraphicsLatency(timeline.inputEventId,
3812 connection->inputChannel->getConnectionToken(),
3813 std::move(timeline.graphicsTimeline));
3814 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003815 }
3816 gotOne = true;
3817 }
3818 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003819 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003820 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 return 1;
3822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 notify = status != DEAD_OBJECT || !connection->monitor;
3826 if (notify) {
3827 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3828 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3829 status);
3830 }
3831 } else {
3832 // Monitor channels are never explicitly unregistered.
3833 // We do it automatically when the remote endpoint is closed so don't warn about them.
3834 const bool stillHaveWindowHandle =
3835 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3836 notify = !connection->monitor && stillHaveWindowHandle;
3837 if (notify) {
3838 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3839 connection->getInputChannelName().c_str(), events);
3840 }
3841 }
3842
3843 // Remove the channel.
3844 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3845 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846}
3847
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003850 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003851 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 }
3853}
3854
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003855void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003856 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003857 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003858 for (const Monitor& monitor : monitors) {
3859 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003860 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003861 }
3862}
3863
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003865 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003866 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003867 if (connection == nullptr) {
3868 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003870
3871 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872}
3873
3874void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003875 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003876 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 return;
3878 }
3879
3880 nsecs_t currentTime = now();
3881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003882 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003883 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003885 if (cancelationEvents.empty()) {
3886 return;
3887 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003888 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3889 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003890 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003891 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003892 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003893 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003894
Arthur Hungb3307ee2021-10-14 10:57:37 +00003895 std::string reason = std::string("reason=").append(options.reason);
3896 android_log_event_list(LOGTAG_INPUT_CANCEL)
3897 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3898
Svet Ganov5d3bc372020-01-26 23:11:07 -08003899 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003900 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003901 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3902 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003903 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003904 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003905 target.globalScaleFactor = windowInfo->globalScaleFactor;
3906 }
3907 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003908 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003909
hongzuo liu95785e22022-09-06 02:51:35 +00003910 const bool wasEmpty = connection->outboundQueue.empty();
3911
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003912 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003913 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003914 switch (cancelationEventEntry->type) {
3915 case EventEntry::Type::KEY: {
3916 logOutboundKeyDetails("cancel - ",
3917 static_cast<const KeyEntry&>(*cancelationEventEntry));
3918 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003920 case EventEntry::Type::MOTION: {
3921 logOutboundMotionDetails("cancel - ",
3922 static_cast<const MotionEntry&>(*cancelationEventEntry));
3923 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003925 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003926 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003927 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3928 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003929 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003930 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003931 break;
3932 }
3933 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003934 case EventEntry::Type::DEVICE_RESET:
3935 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003936 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003937 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003938 break;
3939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 }
3941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003942 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003943 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003945
hongzuo liu95785e22022-09-06 02:51:35 +00003946 // If the outbound queue was previously empty, start the dispatch cycle going.
3947 if (wasEmpty && !connection->outboundQueue.empty()) {
3948 startDispatchCycleLocked(currentTime, connection);
3949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950}
3951
Svet Ganov5d3bc372020-01-26 23:11:07 -08003952void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003953 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003954 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003955 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003956 return;
3957 }
3958
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003959 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003960 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003961
3962 if (downEvents.empty()) {
3963 return;
3964 }
3965
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003966 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003967 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3968 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003969 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003970
3971 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003972 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003973 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3974 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003975 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003976 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003977 target.globalScaleFactor = windowInfo->globalScaleFactor;
3978 }
3979 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003980 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003981
hongzuo liu95785e22022-09-06 02:51:35 +00003982 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003983 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003984 switch (downEventEntry->type) {
3985 case EventEntry::Type::MOTION: {
3986 logOutboundMotionDetails("down - ",
3987 static_cast<const MotionEntry&>(*downEventEntry));
3988 break;
3989 }
3990
3991 case EventEntry::Type::KEY:
3992 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003993 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003994 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003995 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003996 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003997 case EventEntry::Type::SENSOR:
3998 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003999 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004000 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004001 break;
4002 }
4003 }
4004
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004005 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004006 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004007 }
4008
hongzuo liu95785e22022-09-06 02:51:35 +00004009 // If the outbound queue was previously empty, start the dispatch cycle going.
4010 if (wasEmpty && !connection->outboundQueue.empty()) {
4011 startDispatchCycleLocked(downTime, connection);
4012 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004013}
4014
Arthur Hungc539dbb2022-12-08 07:45:36 +00004015void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4016 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4017 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004018 std::shared_ptr<Connection> wallpaperConnection =
4019 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004020 if (wallpaperConnection != nullptr) {
4021 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4022 }
4023 }
4024}
4025
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004026std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004027 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4028 nsecs_t splitDownTime) {
4029 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
4031 uint32_t splitPointerIndexMap[MAX_POINTERS];
4032 PointerProperties splitPointerProperties[MAX_POINTERS];
4033 PointerCoords splitPointerCoords[MAX_POINTERS];
4034
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004035 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 uint32_t splitPointerCount = 0;
4037
4038 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004041 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004043 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4045 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4046 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004047 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 splitPointerCount += 1;
4049 }
4050 }
4051
4052 if (splitPointerCount != pointerIds.count()) {
4053 // This is bad. We are missing some of the pointers that we expected to deliver.
4054 // Most likely this indicates that we received an ACTION_MOVE events that has
4055 // different pointer ids than we expected based on the previous ACTION_DOWN
4056 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4057 // in this way.
4058 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004059 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004060 "a broken sequence of pointer ids from the input device: %s",
4061 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004062 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 }
4064
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004065 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4068 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4070 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004071 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004073 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 if (pointerIds.count() == 1) {
4075 // The first/last pointer went down/up.
4076 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004078 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4079 ? AMOTION_EVENT_ACTION_CANCEL
4080 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 } else {
4082 // A secondary pointer went down/up.
4083 uint32_t splitPointerIndex = 0;
4084 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4085 splitPointerIndex += 1;
4086 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 action = maskedAction |
4088 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 }
4090 } else {
4091 // An unrelated pointer changed.
4092 action = AMOTION_EVENT_ACTION_MOVE;
4093 }
4094 }
4095
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004096 if (action == AMOTION_EVENT_ACTION_DOWN) {
4097 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
4098 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08004099 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4100 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004101 }
4102
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004103 int32_t newId = mIdGenerator.nextId();
4104 if (ATRACE_ENABLED()) {
4105 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4106 ") to MotionEvent(id=0x%" PRIx32 ").",
4107 originalMotionEntry.id, newId);
4108 ATRACE_NAME(message.c_str());
4109 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004110 std::unique_ptr<MotionEntry> splitMotionEntry =
4111 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4112 originalMotionEntry.deviceId, originalMotionEntry.source,
4113 originalMotionEntry.displayId,
4114 originalMotionEntry.policyFlags, action,
4115 originalMotionEntry.actionButton,
4116 originalMotionEntry.flags, originalMotionEntry.metaState,
4117 originalMotionEntry.buttonState,
4118 originalMotionEntry.classification,
4119 originalMotionEntry.edgeFlags,
4120 originalMotionEntry.xPrecision,
4121 originalMotionEntry.yPrecision,
4122 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004123 originalMotionEntry.yCursorPosition, splitDownTime,
4124 splitPointerCount, splitPointerProperties,
4125 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004127 if (originalMotionEntry.injectionState) {
4128 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 splitMotionEntry->injectionState->refCount += 1;
4130 }
4131
4132 return splitMotionEntry;
4133}
4134
Prabir Pradhan678438e2023-04-13 19:32:51 +00004135void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004136 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004137 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139
Antonio Kantekf16f2832021-09-28 04:39:20 +00004140 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004142 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004144 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004145 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 } // release lock
4148
4149 if (needWake) {
4150 mLooper->wake();
4151 }
4152}
4153
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004154/**
4155 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004156 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4157 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4158 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4159 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4160 * potentially handle the back key presses.
4161 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4162 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004163 */
4164void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004166 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4167 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004168 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004169 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004170 }
4171 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004172 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004173 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004174 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004175 keyCode = newKeyCode;
4176 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4177 }
4178 } else if (action == AKEY_EVENT_ACTION_UP) {
4179 // In order to maintain a consistent stream of up and down events, check to see if the key
4180 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4181 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004182 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004183 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004184 auto replacementIt = mReplacedKeys.find(replacement);
4185 if (replacementIt != mReplacedKeys.end()) {
4186 keyCode = replacementIt->second;
4187 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004188 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4189 }
4190 }
4191}
4192
Prabir Pradhan678438e2023-04-13 19:32:51 +00004193void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004194 ALOGD_IF(debugInboundEventDetails(),
4195 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4196 ", deviceId=%d, source=%s, displayId=%" PRId32
4197 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4198 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004199 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4200 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4201 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004202 Result<void> keyCheck = validateKeyEvent(args.action);
4203 if (!keyCheck.ok()) {
4204 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 return;
4206 }
4207
Prabir Pradhan678438e2023-04-13 19:32:51 +00004208 uint32_t policyFlags = args.policyFlags;
4209 int32_t flags = args.flags;
4210 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004211 // InputDispatcher tracks and generates key repeats on behalf of
4212 // whatever notifies it, so repeatCount should always be set to 0
4213 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4215 policyFlags |= POLICY_FLAG_VIRTUAL;
4216 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 if (policyFlags & POLICY_FLAG_FUNCTION) {
4219 metaState |= AMETA_FUNCTION_ON;
4220 }
4221
4222 policyFlags |= POLICY_FLAG_TRUSTED;
4223
Prabir Pradhan678438e2023-04-13 19:32:51 +00004224 int32_t keyCode = args.keyCode;
4225 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004226
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004228 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4229 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4230 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
Michael Wright2b3c3302018-03-02 17:19:13 +00004232 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004233 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004234 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4235 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238
Antonio Kantekf16f2832021-09-28 04:39:20 +00004239 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 { // acquire lock
4241 mLock.lock();
4242
4243 if (shouldSendKeyToInputFilterLocked(args)) {
4244 mLock.unlock();
4245
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004246 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004247 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 return; // event was consumed by the filter
4249 }
4250
4251 mLock.lock();
4252 }
4253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004254 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004255 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4256 args.displayId, policyFlags, args.action, flags, keyCode,
4257 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004259 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 mLock.unlock();
4261 } // release lock
4262
4263 if (needWake) {
4264 mLooper->wake();
4265 }
4266}
4267
Prabir Pradhan678438e2023-04-13 19:32:51 +00004268bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 return mInputFilterEnabled;
4270}
4271
Prabir Pradhan678438e2023-04-13 19:32:51 +00004272void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004273 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004274 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004275 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004276 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004277 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4278 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004279 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4280 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4281 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4282 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4283 args.downTime);
4284 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004285 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4286 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004287 i, args.pointerProperties[i].id,
4288 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4289 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4290 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4291 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4292 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4293 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4294 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4295 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4296 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4297 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004300
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004301 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4302 args.pointerCount, args.pointerProperties);
4303 if (!motionCheck.ok()) {
4304 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004305 return;
4306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Prabir Pradhan678438e2023-04-13 19:32:51 +00004308 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004310
4311 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004312 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004313 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4314 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
Antonio Kantekf16f2832021-09-28 04:39:20 +00004318 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 { // acquire lock
4320 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004321 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4322 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4323 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004324 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004325 if (touchStateIt != mTouchStatesByDisplay.end()) {
4326 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004327 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004328 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4329 }
4330 }
4331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
4333 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004334 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004335 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004336 displayTransform = it->second.transform;
4337 }
4338
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 mLock.unlock();
4340
4341 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004342 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4343 args.action, args.actionButton, args.flags, args.edgeFlags,
4344 args.metaState, args.buttonState, args.classification,
4345 displayTransform, args.xPrecision, args.yPrecision,
4346 args.xCursorPosition, args.yCursorPosition, displayTransform,
4347 args.downTime, args.eventTime, args.pointerCount,
4348 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
4350 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004351 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 return; // event was consumed by the filter
4353 }
4354
4355 mLock.lock();
4356 }
4357
4358 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004360 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4361 args.displayId, policyFlags, args.action,
4362 args.actionButton, args.flags, args.metaState,
4363 args.buttonState, args.classification, args.edgeFlags,
4364 args.xPrecision, args.yPrecision,
4365 args.xCursorPosition, args.yCursorPosition,
4366 args.downTime, args.pointerCount,
4367 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Prabir Pradhan678438e2023-04-13 19:32:51 +00004369 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4370 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004371 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004372 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4373 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004374 }
4375
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004376 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 mLock.unlock();
4378 } // release lock
4379
4380 if (needWake) {
4381 mLooper->wake();
4382 }
4383}
4384
Prabir Pradhan678438e2023-04-13 19:32:51 +00004385void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004386 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004387 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4388 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004389 args.id, args.eventTime, args.deviceId, args.source,
4390 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004391 }
Chris Yef59a2f42020-10-16 12:55:26 -07004392
Antonio Kantekf16f2832021-09-28 04:39:20 +00004393 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004394 { // acquire lock
4395 mLock.lock();
4396
4397 // Just enqueue a new sensor event.
4398 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004399 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4400 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4401 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004402
4403 needWake = enqueueInboundEventLocked(std::move(newEntry));
4404 mLock.unlock();
4405 } // release lock
4406
4407 if (needWake) {
4408 mLooper->wake();
4409 }
4410}
4411
Prabir Pradhan678438e2023-04-13 19:32:51 +00004412void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004413 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004414 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4415 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004416 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004417 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004418}
4419
Prabir Pradhan678438e2023-04-13 19:32:51 +00004420bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004421 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422}
4423
Prabir Pradhan678438e2023-04-13 19:32:51 +00004424void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004425 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004426 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4427 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004428 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430
Prabir Pradhan678438e2023-04-13 19:32:51 +00004431 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004433 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434}
4435
Prabir Pradhan678438e2023-04-13 19:32:51 +00004436void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004437 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004438 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4439 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441
Antonio Kantekf16f2832021-09-28 04:39:20 +00004442 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004444 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004446 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004447 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004448 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 } // release lock
4450
4451 if (needWake) {
4452 mLooper->wake();
4453 }
4454}
4455
Prabir Pradhan678438e2023-04-13 19:32:51 +00004456void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004457 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004458 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4459 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004460 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004461
Antonio Kantekf16f2832021-09-28 04:39:20 +00004462 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004463 { // acquire lock
4464 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004465 auto entry =
4466 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004467 needWake = enqueueInboundEventLocked(std::move(entry));
4468 } // release lock
4469
4470 if (needWake) {
4471 mLooper->wake();
4472 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004473}
4474
Prabir Pradhan5735a322022-04-11 17:23:34 +00004475InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4476 std::optional<int32_t> targetUid,
4477 InputEventInjectionSync syncMode,
4478 std::chrono::milliseconds timeout,
4479 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004480 Result<void> eventValidation = validateInputEvent(*event);
4481 if (!eventValidation.ok()) {
4482 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4483 return InputEventInjectionResult::FAILED;
4484 }
4485
Prabir Pradhan65613802023-02-22 23:36:58 +00004486 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004487 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4488 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4489 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4490 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004491 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004492 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
Prabir Pradhan5735a322022-04-11 17:23:34 +00004494 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004496 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004497 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4498 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4499 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4500 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4501 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004502 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004503 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004504 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004505 }
4506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004507 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004509 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004510 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004511 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004512 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004513 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4514 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4515 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004516 int32_t keyCode = incomingKey.getKeyCode();
4517 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004518 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004519 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004520 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004521 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004522 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4523 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4524 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4527 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004528 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004529
4530 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4531 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004532 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004533 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4534 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4535 std::to_string(t.duration().count()).c_str());
4536 }
4537 }
4538
4539 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004540 std::unique_ptr<KeyEntry> injectedEntry =
4541 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004542 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004543 incomingKey.getDisplayId(), policyFlags, action,
4544 flags, keyCode, incomingKey.getScanCode(), metaState,
4545 incomingKey.getRepeatCount(),
4546 incomingKey.getDownTime());
4547 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004548 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 }
4550
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004551 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004552 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004553 const bool isPointerEvent =
4554 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4555 // If a pointer event has no displayId specified, inject it to the default display.
4556 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4557 ? ADISPLAY_ID_DEFAULT
4558 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004559 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004560
4561 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004562 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004563 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004564 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004565 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4566 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4567 std::to_string(t.duration().count()).c_str());
4568 }
4569 }
4570
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004571 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4572 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4573 }
4574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004576 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4577 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004578 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004579 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4580 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004581 displayId, policyFlags, motionEvent.getAction(),
4582 motionEvent.getActionButton(), flags,
4583 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004584 motionEvent.getButtonState(),
4585 motionEvent.getClassification(),
4586 motionEvent.getEdgeFlags(),
4587 motionEvent.getXPrecision(),
4588 motionEvent.getYPrecision(),
4589 motionEvent.getRawXCursorPosition(),
4590 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004591 motionEvent.getDownTime(),
4592 motionEvent.getPointerCount(),
4593 motionEvent.getPointerProperties(),
4594 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004595 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004596 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004597 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004598 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004599 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004600 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004601 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4602 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004603 displayId, policyFlags,
4604 motionEvent.getAction(),
4605 motionEvent.getActionButton(), flags,
4606 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004607 motionEvent.getButtonState(),
4608 motionEvent.getClassification(),
4609 motionEvent.getEdgeFlags(),
4610 motionEvent.getXPrecision(),
4611 motionEvent.getYPrecision(),
4612 motionEvent.getRawXCursorPosition(),
4613 motionEvent.getRawYCursorPosition(),
4614 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004615 motionEvent.getPointerCount(),
4616 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004617 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004618 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4619 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004620 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 }
4622 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004625 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004626 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004627 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 }
4629
Prabir Pradhan5735a322022-04-11 17:23:34 +00004630 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004631 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 injectionState->injectionIsAsync = true;
4633 }
4634
4635 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004636 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637
4638 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004639 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004640 if (DEBUG_INJECTION) {
4641 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4642 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004643 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004644 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646
4647 mLock.unlock();
4648
4649 if (needWake) {
4650 mLooper->wake();
4651 }
4652
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004653 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004655 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004657 if (syncMode == InputEventInjectionSync::NONE) {
4658 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 } else {
4660 for (;;) {
4661 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004662 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 break;
4664 }
4665
4666 nsecs_t remainingTimeout = endTime - now();
4667 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004668 if (DEBUG_INJECTION) {
4669 ALOGD("injectInputEvent - Timed out waiting for injection result "
4670 "to become available.");
4671 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004672 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 break;
4674 }
4675
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004676 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 }
4678
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004679 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4680 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004682 if (DEBUG_INJECTION) {
4683 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4684 injectionState->pendingForegroundDispatches);
4685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 nsecs_t remainingTimeout = endTime - now();
4687 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004688 if (DEBUG_INJECTION) {
4689 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4690 "dispatches to finish.");
4691 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 break;
4694 }
4695
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004696 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 }
4698 }
4699 }
4700
4701 injectionState->release();
4702 } // release lock
4703
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004704 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004705 LOG(DEBUG) << "injectInputEvent - Finished with result "
4706 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708
4709 return injectionResult;
4710}
4711
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004712std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004713 std::array<uint8_t, 32> calculatedHmac;
4714 std::unique_ptr<VerifiedInputEvent> result;
4715 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004716 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004717 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4718 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4719 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004720 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004721 break;
4722 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004723 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004724 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4725 VerifiedMotionEvent verifiedMotionEvent =
4726 verifiedMotionEventFromMotionEvent(motionEvent);
4727 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004728 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004729 break;
4730 }
4731 default: {
4732 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4733 return nullptr;
4734 }
4735 }
4736 if (calculatedHmac == INVALID_HMAC) {
4737 return nullptr;
4738 }
tyiu1573a672023-02-21 22:38:32 +00004739 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004740 return nullptr;
4741 }
4742 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004743}
4744
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004745void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004746 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004747 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004749 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004750 LOG(DEBUG) << "Setting input event injection result to "
4751 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004754 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 // Log the outcome since the injector did not wait for the injection result.
4756 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004757 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 ALOGV("Asynchronous input event injection succeeded.");
4759 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004760 case InputEventInjectionResult::TARGET_MISMATCH:
4761 ALOGV("Asynchronous input event injection target mismatch.");
4762 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004763 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 ALOGW("Asynchronous input event injection failed.");
4765 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004766 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004767 ALOGW("Asynchronous input event injection timed out.");
4768 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004769 case InputEventInjectionResult::PENDING:
4770 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4771 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773 }
4774
4775 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004776 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 }
4778}
4779
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004780void InputDispatcher::transformMotionEntryForInjectionLocked(
4781 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004782 // Input injection works in the logical display coordinate space, but the input pipeline works
4783 // display space, so we need to transform the injected events accordingly.
4784 const auto it = mDisplayInfos.find(entry.displayId);
4785 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004786 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004787
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004788 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4789 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4790 const vec2 cursor =
4791 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4792 {entry.xCursorPosition, entry.yCursorPosition});
4793 entry.xCursorPosition = cursor.x;
4794 entry.yCursorPosition = cursor.y;
4795 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004796 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004797 entry.pointerCoords[i] =
4798 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4799 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004800 }
4801}
4802
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004803void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4804 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 if (injectionState) {
4806 injectionState->pendingForegroundDispatches += 1;
4807 }
4808}
4809
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004810void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4811 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 if (injectionState) {
4813 injectionState->pendingForegroundDispatches -= 1;
4814
4815 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004816 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 }
4818 }
4819}
4820
chaviw98318de2021-05-19 16:45:23 -05004821const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004822 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004823 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004824 auto it = mWindowHandlesByDisplay.find(displayId);
4825 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004826}
4827
chaviw98318de2021-05-19 16:45:23 -05004828sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004829 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004830 if (windowHandleToken == nullptr) {
4831 return nullptr;
4832 }
4833
Arthur Hungb92218b2018-08-14 12:00:21 +08004834 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004835 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4836 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004837 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004838 return windowHandle;
4839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 }
4841 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004842 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843}
4844
chaviw98318de2021-05-19 16:45:23 -05004845sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4846 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004847 if (windowHandleToken == nullptr) {
4848 return nullptr;
4849 }
4850
chaviw98318de2021-05-19 16:45:23 -05004851 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004852 if (windowHandle->getToken() == windowHandleToken) {
4853 return windowHandle;
4854 }
4855 }
4856 return nullptr;
4857}
4858
chaviw98318de2021-05-19 16:45:23 -05004859sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4860 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004861 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004862 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4863 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004864 if (handle->getId() == windowHandle->getId() &&
4865 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004866 if (windowHandle->getInfo()->displayId != it.first) {
4867 ALOGE("Found window %s in display %" PRId32
4868 ", but it should belong to display %" PRId32,
4869 windowHandle->getName().c_str(), it.first,
4870 windowHandle->getInfo()->displayId);
4871 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004872 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 }
4875 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004876 return nullptr;
4877}
4878
chaviw98318de2021-05-19 16:45:23 -05004879sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004880 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4881 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882}
4883
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004884ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4885 auto displayInfoIt = mDisplayInfos.find(displayId);
4886 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4887 : kIdentityTransform;
4888}
4889
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004890bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4891 const MotionEntry& motionEntry) const {
4892 const WindowInfo& info = *window->getInfo();
4893
4894 // Skip spy window targets that are not valid for targeted injection.
4895 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004896 return false;
4897 }
4898
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004899 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4900 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4901 return false;
4902 }
4903
4904 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4905 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4906 window->getName().c_str());
4907 return false;
4908 }
4909
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004910 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004911 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004912 ALOGW("Not sending touch to %s because there's no corresponding connection",
4913 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004914 return false;
4915 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004916
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004917 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004918 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004919 return false;
4920 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004921
4922 // Drop events that can't be trusted due to occlusion
4923 const auto [x, y] = resolveTouchedPosition(motionEntry);
4924 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4925 if (!isTouchTrustedLocked(occlusionInfo)) {
4926 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004927 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004928 for (const auto& log : occlusionInfo.debugInfo) {
4929 ALOGD("%s", log.c_str());
4930 }
4931 }
4932 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4933 occlusionInfo.obscuringUid);
4934 return false;
4935 }
4936
4937 // Drop touch events if requested by input feature
4938 if (shouldDropInput(motionEntry, window)) {
4939 return false;
4940 }
4941
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004942 return true;
4943}
4944
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004945std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4946 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004947 auto connectionIt = mConnectionsByToken.find(token);
4948 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004949 return nullptr;
4950 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004951 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004952}
4953
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004954void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004955 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4956 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004957 // Remove all handles on a display if there are no windows left.
4958 mWindowHandlesByDisplay.erase(displayId);
4959 return;
4960 }
4961
4962 // Since we compare the pointer of input window handles across window updates, we need
4963 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004964 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4965 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4966 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004967 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004968 }
4969
chaviw98318de2021-05-19 16:45:23 -05004970 std::vector<sp<WindowInfoHandle>> newHandles;
4971 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004972 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004973 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004974 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004975 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004976 const bool canReceiveInput =
4977 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4978 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004979 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004980 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004981 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004982 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004983 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004984 }
4985
4986 if (info->displayId != displayId) {
4987 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4988 handle->getName().c_str(), displayId, info->displayId);
4989 continue;
4990 }
4991
Robert Carredd13602020-04-13 17:24:34 -07004992 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4993 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004994 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004995 oldHandle->updateFrom(handle);
4996 newHandles.push_back(oldHandle);
4997 } else {
4998 newHandles.push_back(handle);
4999 }
5000 }
5001
5002 // Insert or replace
5003 mWindowHandlesByDisplay[displayId] = newHandles;
5004}
5005
Arthur Hung72d8dc32020-03-28 00:48:39 +00005006void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005007 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005008 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005009 { // acquire lock
5010 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005011 for (const auto& [displayId, handles] : handlesPerDisplay) {
5012 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005013 }
5014 }
5015 // Wake up poll loop since it may need to make new input dispatching choices.
5016 mLooper->wake();
5017}
5018
Arthur Hungb92218b2018-08-14 12:00:21 +08005019/**
5020 * Called from InputManagerService, update window handle list by displayId that can receive input.
5021 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5022 * If set an empty list, remove all handles from the specific display.
5023 * For focused handle, check if need to change and send a cancel event to previous one.
5024 * For removed handle, check if need to send a cancel event if already in touch.
5025 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005026void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005027 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005028 if (DEBUG_FOCUS) {
5029 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005030 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005031 windowList += iwh->getName() + " ";
5032 }
5033 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035
Prabir Pradhand65552b2021-10-07 11:23:50 -07005036 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005037 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005038 const WindowInfo& info = *window->getInfo();
5039
5040 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005041 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005042 if (noInputWindow && window->getToken() != nullptr) {
5043 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5044 window->getName().c_str());
5045 window->releaseChannel();
5046 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005047
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005048 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005049 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5050 !info.inputConfig.test(
5051 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005052 "%s has feature SPY, but is not a trusted overlay.",
5053 window->getName().c_str());
5054
Prabir Pradhand65552b2021-10-07 11:23:50 -07005055 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005056 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5057 !info.inputConfig.test(
5058 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005059 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5060 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005061 }
5062
Arthur Hung72d8dc32020-03-28 00:48:39 +00005063 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005064 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005066 // Save the old windows' orientation by ID before it gets updated.
5067 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005068 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005069 oldWindowOrientations.emplace(handle->getId(),
5070 handle->getInfo()->transform.getOrientation());
5071 }
5072
chaviw98318de2021-05-19 16:45:23 -05005073 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005074
chaviw98318de2021-05-19 16:45:23 -05005075 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005076
Vishnu Nairc519ff72021-01-21 08:23:08 -08005077 std::optional<FocusResolver::FocusChanges> changes =
5078 mFocusResolver.setInputWindows(displayId, windowHandles);
5079 if (changes) {
5080 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005083 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5084 mTouchStatesByDisplay.find(displayId);
5085 if (stateIt != mTouchStatesByDisplay.end()) {
5086 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005087 for (size_t i = 0; i < state.windows.size();) {
5088 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005089 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005091 ALOGD("Touched window was removed: %s in display %" PRId32,
5092 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005093 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005094 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005095 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5096 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005097 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005098 "touched window was removed");
5099 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005100 // Since we are about to drop the touch, cancel the events for the wallpaper as
5101 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005102 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005103 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5104 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005105 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005106 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005109 state.windows.erase(state.windows.begin() + i);
5110 } else {
5111 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113 }
arthurhungb89ccb02020-12-30 16:19:01 +08005114
arthurhung6d4bed92021-03-17 11:59:33 +08005115 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005116 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005117 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005118 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005119 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005120 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5121 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005122 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005123 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005124 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005125
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005126 // Determine if the orientation of any of the input windows have changed, and cancel all
5127 // pointer events if necessary.
5128 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5129 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5130 if (newWindowHandle != nullptr &&
5131 newWindowHandle->getInfo()->transform.getOrientation() !=
5132 oldWindowOrientations[oldWindowHandle->getId()]) {
5133 std::shared_ptr<InputChannel> inputChannel =
5134 getInputChannelLocked(newWindowHandle->getToken());
5135 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005136 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005137 "touched window's orientation changed");
5138 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005139 }
5140 }
5141 }
5142
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 // Release information for windows that are no longer present.
5144 // This ensures that unused input channels are released promptly.
5145 // Otherwise, they might stick around until the window handle is destroyed
5146 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005147 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005148 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005149 if (DEBUG_FOCUS) {
5150 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005151 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005152 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005153 }
chaviw291d88a2019-02-14 10:33:58 -08005154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155}
5156
5157void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005158 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005159 if (DEBUG_FOCUS) {
5160 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5161 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5162 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005163 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005164 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005165 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 } // release lock
5167
5168 // Wake up poll loop since it may need to make new input dispatching choices.
5169 mLooper->wake();
5170}
5171
Vishnu Nair599f1412021-06-21 10:39:58 -07005172void InputDispatcher::setFocusedApplicationLocked(
5173 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5174 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5175 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5176
5177 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5178 return; // This application is already focused. No need to wake up or change anything.
5179 }
5180
5181 // Set the new application handle.
5182 if (inputApplicationHandle != nullptr) {
5183 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5184 } else {
5185 mFocusedApplicationHandlesByDisplay.erase(displayId);
5186 }
5187
5188 // No matter what the old focused application was, stop waiting on it because it is
5189 // no longer focused.
5190 resetNoFocusedWindowTimeoutLocked();
5191}
5192
Tiger Huang721e26f2018-07-24 22:26:19 +08005193/**
5194 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5195 * the display not specified.
5196 *
5197 * We track any unreleased events for each window. If a window loses the ability to receive the
5198 * released event, we will send a cancel event to it. So when the focused display is changed, we
5199 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5200 * display. The display-specified events won't be affected.
5201 */
5202void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005203 if (DEBUG_FOCUS) {
5204 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5205 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005206 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005207 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005208
5209 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005210 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005211 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005212 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005213 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005214 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005215 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005216 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005217 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005218 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005219 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005220 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5221 }
5222 }
5223 mFocusedDisplayId = displayId;
5224
Chris Ye3c2d6f52020-08-09 10:39:48 -07005225 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005226 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005227 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005228
Vishnu Nairad321cd2020-08-20 16:40:21 -07005229 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005230 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005231 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005232 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005233 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005234 }
5235 }
5236 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005237 } // release lock
5238
5239 // Wake up poll loop since it may need to make new input dispatching choices.
5240 mLooper->wake();
5241}
5242
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005244 if (DEBUG_FOCUS) {
5245 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247
5248 bool changed;
5249 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005250 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
5252 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5253 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005254 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 }
5256
5257 if (mDispatchEnabled && !enabled) {
5258 resetAndDropEverythingLocked("dispatcher is being disabled");
5259 }
5260
5261 mDispatchEnabled = enabled;
5262 mDispatchFrozen = frozen;
5263 changed = true;
5264 } else {
5265 changed = false;
5266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 } // release lock
5268
5269 if (changed) {
5270 // Wake up poll loop since it may need to make new input dispatching choices.
5271 mLooper->wake();
5272 }
5273}
5274
5275void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005276 if (DEBUG_FOCUS) {
5277 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279
5280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005281 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282
5283 if (mInputFilterEnabled == enabled) {
5284 return;
5285 }
5286
5287 mInputFilterEnabled = enabled;
5288 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5289 } // release lock
5290
5291 // Wake up poll loop since there might be work to do to drop everything.
5292 mLooper->wake();
5293}
5294
Antonio Kanteka042c022022-07-06 16:51:07 -07005295bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5296 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005297 bool needWake = false;
5298 {
5299 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005300 ALOGD_IF(DEBUG_TOUCH_MODE,
5301 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5302 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5303 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5304 mTouchModePerDisplay.count(displayId) == 0
5305 ? "not set"
5306 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5307
Antonio Kantek15beb512022-06-13 22:35:41 +00005308 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5309 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005310 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005311 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005312 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005313 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5314 !recentWindowsAreOwnedByLocked(pid, uid)) {
5315 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5316 "window nor none of the previously interacted window",
5317 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005318 return false;
5319 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005320 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005321 mTouchModePerDisplay[displayId] = inTouchMode;
5322 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5323 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005324 needWake = enqueueInboundEventLocked(std::move(entry));
5325 } // release lock
5326
5327 if (needWake) {
5328 mLooper->wake();
5329 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005330 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005331}
5332
Antonio Kantek48710e42022-03-24 14:19:30 -07005333bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5334 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5335 if (focusedToken == nullptr) {
5336 return false;
5337 }
5338 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5339 return isWindowOwnedBy(windowHandle, pid, uid);
5340}
5341
5342bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5343 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5344 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5345 const sp<WindowInfoHandle> windowHandle =
5346 getWindowHandleLocked(connectionToken);
5347 return isWindowOwnedBy(windowHandle, pid, uid);
5348 }) != mInteractionConnectionTokens.end();
5349}
5350
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005351void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5352 if (opacity < 0 || opacity > 1) {
5353 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5354 return;
5355 }
5356
5357 std::scoped_lock lock(mLock);
5358 mMaximumObscuringOpacityForTouch = opacity;
5359}
5360
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005361std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5362InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005363 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5364 for (TouchedWindow& w : state.windows) {
5365 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005366 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005367 }
5368 }
5369 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005370 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005371}
5372
arthurhungb89ccb02020-12-30 16:19:01 +08005373bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5374 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005375 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005376 if (DEBUG_FOCUS) {
5377 ALOGD("Trivial transfer to same window.");
5378 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005379 return true;
5380 }
5381
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005383 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384
Arthur Hungabbb9d82021-09-01 14:52:30 +00005385 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005386 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005387 if (state == nullptr || touchedWindow == nullptr) {
5388 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 return false;
5390 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005391
Arthur Hungabbb9d82021-09-01 14:52:30 +00005392 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5393 if (toWindowHandle == nullptr) {
5394 ALOGW("Cannot transfer focus because to window not found.");
5395 return false;
5396 }
5397
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005398 if (DEBUG_FOCUS) {
5399 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005400 touchedWindow->windowHandle->getName().c_str(),
5401 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403
Arthur Hungabbb9d82021-09-01 14:52:30 +00005404 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005405 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005406 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005407 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005408 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409
Arthur Hungabbb9d82021-09-01 14:52:30 +00005410 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005411 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005412 ftl::Flags<InputTarget::Flags> newTargetFlags =
5413 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005414 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005415 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005416 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005417 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
Arthur Hungabbb9d82021-09-01 14:52:30 +00005419 // Store the dragging window.
5420 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005421 if (pointerIds.count() != 1) {
5422 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5423 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005424 return false;
5425 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005426 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005427 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005428 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430
Arthur Hungabbb9d82021-09-01 14:52:30 +00005431 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005432 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5433 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005434 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005435 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005436 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005437 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005438 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005440 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5441 newTargetFlags);
5442
5443 // Check if the wallpaper window should deliver the corresponding event.
5444 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5445 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 } // release lock
5448
5449 // Wake up poll loop since it may need to make new input dispatching choices.
5450 mLooper->wake();
5451 return true;
5452}
5453
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005454/**
5455 * Get the touched foreground window on the given display.
5456 * Return null if there are no windows touched on that display, or if more than one foreground
5457 * window is being touched.
5458 */
5459sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5460 auto stateIt = mTouchStatesByDisplay.find(displayId);
5461 if (stateIt == mTouchStatesByDisplay.end()) {
5462 ALOGI("No touch state on display %" PRId32, displayId);
5463 return nullptr;
5464 }
5465
5466 const TouchState& state = stateIt->second;
5467 sp<WindowInfoHandle> touchedForegroundWindow;
5468 // If multiple foreground windows are touched, return nullptr
5469 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005470 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005471 if (touchedForegroundWindow != nullptr) {
5472 ALOGI("Two or more foreground windows: %s and %s",
5473 touchedForegroundWindow->getName().c_str(),
5474 window.windowHandle->getName().c_str());
5475 return nullptr;
5476 }
5477 touchedForegroundWindow = window.windowHandle;
5478 }
5479 }
5480 return touchedForegroundWindow;
5481}
5482
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005483// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005484bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005485 sp<IBinder> fromToken;
5486 { // acquire lock
5487 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005488 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005489 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005490 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5491 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005492 return false;
5493 }
5494
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005495 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5496 if (from == nullptr) {
5497 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5498 return false;
5499 }
5500
5501 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005502 } // release lock
5503
5504 return transferTouchFocus(fromToken, destChannelToken);
5505}
5506
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005508 if (DEBUG_FOCUS) {
5509 ALOGD("Resetting and dropping all events (%s).", reason);
5510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511
Michael Wrightfb04fd52022-11-24 22:31:11 +00005512 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 synthesizeCancelationEventsForAllConnectionsLocked(options);
5514
5515 resetKeyRepeatLocked();
5516 releasePendingEventLocked();
5517 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005518 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005520 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005521 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005522 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523}
5524
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005525void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005526 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 dumpDispatchStateLocked(dump);
5528
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005529 std::istringstream stream(dump);
5530 std::string line;
5531
5532 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005533 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 }
5535}
5536
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005537std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005538 std::string dump;
5539
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005540 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5541 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005542
5543 std::string windowName = "None";
5544 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005545 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005546 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5547 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5548 : "token has capture without window";
5549 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005550 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005551
5552 return dump;
5553}
5554
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005555void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005556 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5557 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5558 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005559 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560
Tiger Huang721e26f2018-07-24 22:26:19 +08005561 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5562 dump += StringPrintf(INDENT "FocusedApplications:\n");
5563 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5564 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005565 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005566 const std::chrono::duration timeout =
5567 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005568 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005569 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005570 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005573 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005575
Vishnu Nairc519ff72021-01-21 08:23:08 -08005576 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005577 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005579 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005580 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005581 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005582 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5583 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 }
5585 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005586 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 }
5588
arthurhung6d4bed92021-03-17 11:59:33 +08005589 if (mDragState) {
5590 dump += StringPrintf(INDENT "DragState:\n");
5591 mDragState->dump(dump, INDENT2);
5592 }
5593
Arthur Hungb92218b2018-08-14 12:00:21 +08005594 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005595 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5596 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5597 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5598 const auto& displayInfo = it->second;
5599 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5600 displayInfo.logicalHeight);
5601 displayInfo.transform.dump(dump, "transform", INDENT4);
5602 } else {
5603 dump += INDENT2 "No DisplayInfo found!\n";
5604 }
5605
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005606 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005607 dump += INDENT2 "Windows:\n";
5608 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005609 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5610 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005612 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005613 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005614 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005615 "applicationInfo.name=%s, "
5616 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005617 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005618 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005619 windowInfo->displayId,
5620 windowInfo->inputConfig.string().c_str(),
5621 windowInfo->alpha, windowInfo->frameLeft,
5622 windowInfo->frameTop, windowInfo->frameRight,
5623 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005624 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005625 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005626 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005627 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005628 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005629 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005630 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005631 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005632 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005633 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005634 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005635 }
5636 } else {
5637 dump += INDENT2 "Windows: <none>\n";
5638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 }
5640 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005641 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 }
Patrick Williamsd828f302023-04-28 17:52:08 -05005643 dump += INDENT "Window Infos:\n";
5644 dump += StringPrintf(INDENT2 "vsync id: %" PRId64 "\n", mWindowInfosVsyncId);
5645 dump += StringPrintf(INDENT2 "timestamp (ns): %" PRId64 "\n", mWindowInfosTimestamp);
5646 dump += "\n";
5647 dump += StringPrintf(INDENT2 "max update delay (ns): %" PRId64 "\n", mMaxWindowInfosDelay);
5648 dump += StringPrintf(INDENT2 "max update delay vsync id: %" PRId64 "\n",
5649 mMaxWindowInfosDelayVsyncId);
5650 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005652 if (!mGlobalMonitorsByDisplay.empty()) {
5653 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5654 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005655 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005658 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 }
5660
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662
5663 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005664 if (!mRecentQueue.empty()) {
5665 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005666 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005667 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005668 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005669 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 }
5671 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005672 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673 }
5674
5675 // Dump event currently being dispatched.
5676 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005677 dump += INDENT "PendingEvent:\n";
5678 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005679 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005680 dump += StringPrintf(", age=%" PRId64 "ms\n",
5681 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685
5686 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005687 if (!mInboundQueue.empty()) {
5688 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005689 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005690 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005691 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005692 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 }
5694 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005695 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 }
5697
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005698 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005699 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005700 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005701 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005702 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005703 }
5704 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005705 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005706 }
5707
Prabir Pradhancef936d2021-07-21 16:17:52 +00005708 if (!mCommandQueue.empty()) {
5709 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5710 } else {
5711 dump += INDENT "CommandQueue: <empty>\n";
5712 }
5713
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005714 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005715 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005716 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005717 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005718 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005719 connection->inputChannel->getFd().get(),
5720 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005721 connection->getWindowName().c_str(),
5722 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005723 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005725 if (!connection->outboundQueue.empty()) {
5726 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5727 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005728 dump += dumpQueue(connection->outboundQueue, currentTime);
5729
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005731 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005734 if (!connection->waitQueue.empty()) {
5735 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5736 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005737 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005739 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741 }
5742 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005743 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
5745
5746 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005747 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5748 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
5752
Antonio Kantek15beb512022-06-13 22:35:41 +00005753 if (!mTouchModePerDisplay.empty()) {
5754 dump += INDENT "TouchModePerDisplay:\n";
5755 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5756 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5757 std::to_string(touchMode).c_str());
5758 }
5759 } else {
5760 dump += INDENT "TouchModePerDisplay: <none>\n";
5761 }
5762
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005763 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005764 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5765 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5766 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005767 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005768 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769}
5770
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005771void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005772 const size_t numMonitors = monitors.size();
5773 for (size_t i = 0; i < numMonitors; i++) {
5774 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005775 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005776 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5777 dump += "\n";
5778 }
5779}
5780
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005781class LooperEventCallback : public LooperCallback {
5782public:
5783 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5784 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5785
5786private:
5787 std::function<int(int events)> mCallback;
5788};
5789
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005790Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005791 if (DEBUG_CHANNEL_CREATION) {
5792 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005795 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005796 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005797 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005798
5799 if (result) {
5800 return base::Error(result) << "Failed to open input channel pair with name " << name;
5801 }
5802
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005804 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005805 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005806 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005807 std::shared_ptr<Connection> connection =
5808 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5809 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005811 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5812 ALOGE("Created a new connection, but the token %p is already known", token.get());
5813 }
5814 mConnectionsByToken.emplace(token, connection);
5815
5816 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5817 this, std::placeholders::_1, token);
5818
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005819 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5820 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 } // release lock
5822
5823 // Wake the looper because some connections have changed.
5824 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005825 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826}
5827
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005828Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005829 const std::string& name,
5830 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005831 std::shared_ptr<InputChannel> serverChannel;
5832 std::unique_ptr<InputChannel> clientChannel;
5833 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5834 if (result) {
5835 return base::Error(result) << "Failed to open input channel pair with name " << name;
5836 }
5837
Michael Wright3dd60e22019-03-27 22:06:44 +00005838 { // acquire lock
5839 std::scoped_lock _l(mLock);
5840
5841 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005842 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5843 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005844 }
5845
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005846 std::shared_ptr<Connection> connection =
5847 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005849 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005850
5851 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5852 ALOGE("Created a new connection, but the token %p is already known", token.get());
5853 }
5854 mConnectionsByToken.emplace(token, connection);
5855 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5856 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005857
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005858 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005859
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005860 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5861 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005862 }
Garfield Tan15601662020-09-22 15:32:38 -07005863
Michael Wright3dd60e22019-03-27 22:06:44 +00005864 // Wake the looper because some connections have changed.
5865 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005866 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005867}
5868
Garfield Tan15601662020-09-22 15:32:38 -07005869status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005871 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872
Harry Cutts33476232023-01-30 19:57:29 +00005873 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 if (status) {
5875 return status;
5876 }
5877 } // release lock
5878
5879 // Wake the poll loop because removing the connection may have changed the current
5880 // synchronization state.
5881 mLooper->wake();
5882 return OK;
5883}
5884
Garfield Tan15601662020-09-22 15:32:38 -07005885status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5886 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005887 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005888 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005889 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890 return BAD_VALUE;
5891 }
5892
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005893 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005894
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005896 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 }
5898
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005899 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900
5901 nsecs_t currentTime = now();
5902 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5903
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005904 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905 return OK;
5906}
5907
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005908void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005909 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5910 auto& [displayId, monitors] = *it;
5911 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5912 return monitor.inputChannel->getConnectionToken() == connectionToken;
5913 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005914
Michael Wright3dd60e22019-03-27 22:06:44 +00005915 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005916 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005917 } else {
5918 ++it;
5919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 }
5921}
5922
Michael Wright3dd60e22019-03-27 22:06:44 +00005923status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005924 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005925 return pilferPointersLocked(token);
5926}
Michael Wright3dd60e22019-03-27 22:06:44 +00005927
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005928status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005929 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5930 if (!requestingChannel) {
5931 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5932 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005933 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005934
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005935 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005936 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005937 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5938 " Ignoring.");
5939 return BAD_VALUE;
5940 }
5941
5942 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005943 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005944 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005945 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005946 "input channel stole pointer stream");
5947 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005948 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005949 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005950 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005951 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005952 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005953 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005954 if (channel != nullptr && channel->getConnectionToken() != token) {
5955 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5956 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5957 canceledWindows += channel->getName();
5958 }
5959 }
5960 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5961 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5962 canceledWindows.c_str());
5963
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005964 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005965 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005966 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005967
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005968 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005969 return OK;
5970}
5971
Prabir Pradhan99987712020-11-10 18:43:05 -08005972void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5973 { // acquire lock
5974 std::scoped_lock _l(mLock);
5975 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005976 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005977 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5978 windowHandle != nullptr ? windowHandle->getName().c_str()
5979 : "token without window");
5980 }
5981
Vishnu Nairc519ff72021-01-21 08:23:08 -08005982 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005983 if (focusedToken != windowToken) {
5984 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5985 enabled ? "enable" : "disable");
5986 return;
5987 }
5988
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005989 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005990 ALOGW("Ignoring request to %s Pointer Capture: "
5991 "window has %s requested pointer capture.",
5992 enabled ? "enable" : "disable", enabled ? "already" : "not");
5993 return;
5994 }
5995
Christine Franksb768bb42021-11-29 12:11:31 -08005996 if (enabled) {
5997 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5998 mIneligibleDisplaysForPointerCapture.end(),
5999 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6000 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6001 return;
6002 }
6003 }
6004
Prabir Pradhan99987712020-11-10 18:43:05 -08006005 setPointerCaptureLocked(enabled);
6006 } // release lock
6007
6008 // Wake the thread to process command entries.
6009 mLooper->wake();
6010}
6011
Christine Franksb768bb42021-11-29 12:11:31 -08006012void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6013 { // acquire lock
6014 std::scoped_lock _l(mLock);
6015 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6016 if (!isEligible) {
6017 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6018 }
6019 } // release lock
6020}
6021
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006022std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
6023 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006024 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006025 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006026 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006027 }
6028 }
6029 }
6030 return std::nullopt;
6031}
6032
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006033std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6034 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006035 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006036 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006037 }
6038
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006039 for (const auto& [token, connection] : mConnectionsByToken) {
6040 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006041 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 }
6043 }
Robert Carr4e670e52018-08-15 13:26:12 -07006044
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006045 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046}
6047
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006048std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006049 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006050 if (connection == nullptr) {
6051 return "<nullptr>";
6052 }
6053 return connection->getInputChannelName();
6054}
6055
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006056void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006057 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006058 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006059}
6060
Prabir Pradhancef936d2021-07-21 16:17:52 +00006061void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006062 const std::shared_ptr<Connection>& connection,
6063 uint32_t seq, bool handled,
6064 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006065 // Handle post-event policy actions.
6066 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6067 if (dispatchEntryIt == connection->waitQueue.end()) {
6068 return;
6069 }
6070 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6071 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6072 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6073 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6074 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6075 }
6076 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6077 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6078 connection->inputChannel->getConnectionToken(),
6079 dispatchEntry->deliveryTime, consumeTime, finishTime);
6080 }
6081
6082 bool restartEvent;
6083 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6084 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6085 restartEvent =
6086 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6087 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6088 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6089 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6090 handled);
6091 } else {
6092 restartEvent = false;
6093 }
6094
6095 // Dequeue the event and start the next cycle.
6096 // Because the lock might have been released, it is possible that the
6097 // contents of the wait queue to have been drained, so we need to double-check
6098 // a few things.
6099 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6100 if (dispatchEntryIt != connection->waitQueue.end()) {
6101 dispatchEntry = *dispatchEntryIt;
6102 connection->waitQueue.erase(dispatchEntryIt);
6103 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6104 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6105 if (!connection->responsive) {
6106 connection->responsive = isConnectionResponsive(*connection);
6107 if (connection->responsive) {
6108 // The connection was unresponsive, and now it's responsive.
6109 processConnectionResponsiveLocked(*connection);
6110 }
6111 }
6112 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006113 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006114 connection->outboundQueue.push_front(dispatchEntry);
6115 traceOutboundQueueLength(*connection);
6116 } else {
6117 releaseDispatchEntry(dispatchEntry);
6118 }
6119 }
6120
6121 // Start the next dispatch cycle for this connection.
6122 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123}
6124
Prabir Pradhancef936d2021-07-21 16:17:52 +00006125void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6126 const sp<IBinder>& newToken) {
6127 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6128 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006129 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006130 };
6131 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006132}
6133
Prabir Pradhancef936d2021-07-21 16:17:52 +00006134void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6135 auto command = [this, token, x, y]() REQUIRES(mLock) {
6136 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006137 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006138 };
6139 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006140}
6141
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006142void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006143 if (connection == nullptr) {
6144 LOG_ALWAYS_FATAL("Caller must check for nullness");
6145 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006146 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6147 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006148 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006149 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006150 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006151 return;
6152 }
6153 /**
6154 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6155 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6156 * has changed. This could cause newer entries to time out before the already dispatched
6157 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6158 * processes the events linearly. So providing information about the oldest entry seems to be
6159 * most useful.
6160 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006161 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006162 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6163 std::string reason =
6164 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006166 ns2ms(currentWait),
6167 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006168 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006169 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006170
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006171 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6172
6173 // Stop waking up for events on this connection, it is already unresponsive
6174 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006175}
6176
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006177void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6178 std::string reason =
6179 StringPrintf("%s does not have a focused window", application->getName().c_str());
6180 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006181
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6183 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006184 mPolicy.notifyNoFocusedWindowAnr(application);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006185 };
6186 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006187}
6188
chaviw98318de2021-05-19 16:45:23 -05006189void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006190 const std::string& reason) {
6191 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6192 updateLastAnrStateLocked(windowLabel, reason);
6193}
6194
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006195void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6196 const std::string& reason) {
6197 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006198 updateLastAnrStateLocked(windowLabel, reason);
6199}
6200
6201void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6202 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006204 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 struct tm tm;
6206 localtime_r(&t, &tm);
6207 char timestr[64];
6208 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006209 mLastAnrState.clear();
6210 mLastAnrState += INDENT "ANR:\n";
6211 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006212 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6213 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006214 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215}
6216
Prabir Pradhancef936d2021-07-21 16:17:52 +00006217void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6218 KeyEntry& entry) {
6219 const KeyEvent event = createKeyEvent(entry);
6220 nsecs_t delay = 0;
6221 { // release lock
6222 scoped_unlock unlock(mLock);
6223 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006224 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006225 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6226 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6227 std::to_string(t.duration().count()).c_str());
6228 }
6229 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230
6231 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006232 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006233 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006234 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006236 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006237 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239}
6240
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006242 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006243 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006244 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006245 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006246 mPolicy.notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006247 };
6248 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006249}
6250
Prabir Pradhanedd96402022-02-15 01:46:16 -08006251void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6252 std::optional<int32_t> pid) {
6253 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006254 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006255 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256 };
6257 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006258}
6259
6260/**
6261 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6262 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6263 * command entry to the command queue.
6264 */
6265void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6266 std::string reason) {
6267 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006268 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006269 if (connection.monitor) {
6270 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6271 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006272 pid = findMonitorPidByTokenLocked(connectionToken);
6273 } else {
6274 // The connection is a window
6275 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6276 reason.c_str());
6277 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6278 if (handle != nullptr) {
6279 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006280 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006281 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006282 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006283}
6284
6285/**
6286 * Tell the policy that a connection has become responsive so that it can stop ANR.
6287 */
6288void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6289 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006290 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006291 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006292 pid = findMonitorPidByTokenLocked(connectionToken);
6293 } else {
6294 // The connection is a window
6295 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6296 if (handle != nullptr) {
6297 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006298 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006299 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006300 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006301}
6302
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006303bool InputDispatcher::afterKeyEventLockedInterruptable(
6304 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6305 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006306 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006307 if (!handled) {
6308 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006309 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006310 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006311 return false;
6312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006314 // Get the fallback key state.
6315 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006316 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006317 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006318 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006319 connection->inputState.removeFallbackKey(originalKeyCode);
6320 }
6321
6322 if (handled || !dispatchEntry->hasForegroundTarget()) {
6323 // If the application handles the original key for which we previously
6324 // generated a fallback or if the window is not a foreground window,
6325 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006326 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006327 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006328 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6329 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6330 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6331 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6332 keyEntry.policyFlags);
6333 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006334 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006335 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336
6337 mLock.unlock();
6338
Prabir Pradhana41d2442023-04-20 21:30:40 +00006339 if (const auto unhandledKeyFallback =
6340 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6341 event, keyEntry.policyFlags);
6342 unhandledKeyFallback) {
6343 event = *unhandledKeyFallback;
6344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345
6346 mLock.lock();
6347
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006348 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006349 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006350 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006351 "application handled the original non-fallback key "
6352 "or is no longer a foreground target, "
6353 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006354 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006355 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006356 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006357 connection->inputState.removeFallbackKey(originalKeyCode);
6358 }
6359 } else {
6360 // If the application did not handle a non-fallback key, first check
6361 // that we are in a good state to perform unhandled key event processing
6362 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006363 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006364 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006365 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6366 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6367 "since this is not an initial down. "
6368 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6369 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6370 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006371 return false;
6372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006374 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006375 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6376 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6377 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6378 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6379 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006380 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006381
6382 mLock.unlock();
6383
Prabir Pradhana41d2442023-04-20 21:30:40 +00006384 bool fallback = false;
6385 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6386 event, keyEntry.policyFlags);
6387 fb) {
6388 fallback = true;
6389 event = *fb;
6390 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006391
6392 mLock.lock();
6393
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006394 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006395 connection->inputState.removeFallbackKey(originalKeyCode);
6396 return false;
6397 }
6398
6399 // Latch the fallback keycode for this key on an initial down.
6400 // The fallback keycode cannot change at any other point in the lifecycle.
6401 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006403 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006405 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006406 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006407 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 }
6409
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006410 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006411
6412 // Cancel the fallback key if the policy decides not to send it anymore.
6413 // We will continue to dispatch the key to the policy but we will no
6414 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006415 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6416 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006417 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6418 if (fallback) {
6419 ALOGD("Unhandled key event: Policy requested to send key %d"
6420 "as a fallback for %d, but on the DOWN it had requested "
6421 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006422 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006423 } else {
6424 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6425 "but on the DOWN it had requested to send %d. "
6426 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006427 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006428 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006429 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430
Michael Wrightfb04fd52022-11-24 22:31:11 +00006431 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006433 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006434 synthesizeCancelationEventsForConnectionLocked(connection, options);
6435
6436 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006437 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006438 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006439 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440 }
6441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006443 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6444 {
6445 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006446 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006447 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006448 for (const auto& [key, value] : fallbackKeys) {
6449 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006450 }
6451 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6452 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455
6456 if (fallback) {
6457 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006458 keyEntry.eventTime = event.getEventTime();
6459 keyEntry.deviceId = event.getDeviceId();
6460 keyEntry.source = event.getSource();
6461 keyEntry.displayId = event.getDisplayId();
6462 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006464 keyEntry.scanCode = event.getScanCode();
6465 keyEntry.metaState = event.getMetaState();
6466 keyEntry.repeatCount = event.getRepeatCount();
6467 keyEntry.downTime = event.getDownTime();
6468 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006469
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006470 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6471 ALOGD("Unhandled key event: Dispatching fallback key. "
6472 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006475 return true; // restart the event
6476 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006477 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6478 ALOGD("Unhandled key event: No fallback key.");
6479 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006480
6481 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006482 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483 }
6484 }
6485 return false;
6486}
6487
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006488bool InputDispatcher::afterMotionEventLockedInterruptable(
6489 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6490 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006491 return false;
6492}
6493
Michael Wrightd02c5b62014-02-10 15:10:22 -08006494void InputDispatcher::traceInboundQueueLengthLocked() {
6495 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006496 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006497 }
6498}
6499
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006500void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 if (ATRACE_ENABLED()) {
6502 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006503 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6504 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 }
6506}
6507
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006508void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006509 if (ATRACE_ENABLED()) {
6510 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006511 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6512 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513 }
6514}
6515
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006516void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006517 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006519 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006520 dumpDispatchStateLocked(dump);
6521
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006522 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006523 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006524 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006525 }
6526}
6527
6528void InputDispatcher::monitor() {
6529 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006530 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006532 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006533}
6534
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006535/**
6536 * Wake up the dispatcher and wait until it processes all events and commands.
6537 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6538 * this method can be safely called from any thread, as long as you've ensured that
6539 * the work you are interested in completing has already been queued.
6540 */
6541bool InputDispatcher::waitForIdle() {
6542 /**
6543 * Timeout should represent the longest possible time that a device might spend processing
6544 * events and commands.
6545 */
6546 constexpr std::chrono::duration TIMEOUT = 100ms;
6547 std::unique_lock lock(mLock);
6548 mLooper->wake();
6549 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6550 return result == std::cv_status::no_timeout;
6551}
6552
Vishnu Naire798b472020-07-23 13:52:21 -07006553/**
6554 * Sets focus to the window identified by the token. This must be called
6555 * after updating any input window handles.
6556 *
6557 * Params:
6558 * request.token - input channel token used to identify the window that should gain focus.
6559 * request.focusedToken - the token that the caller expects currently to be focused. If the
6560 * specified token does not match the currently focused window, this request will be dropped.
6561 * If the specified focused token matches the currently focused window, the call will succeed.
6562 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6563 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6564 * when requesting the focus change. This determines which request gets
6565 * precedence if there is a focus change request from another source such as pointer down.
6566 */
Vishnu Nair958da932020-08-21 17:12:37 -07006567void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6568 { // acquire lock
6569 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006570 std::optional<FocusResolver::FocusChanges> changes =
6571 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6572 if (changes) {
6573 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006574 }
6575 } // release lock
6576 // Wake up poll loop since it may need to make new input dispatching choices.
6577 mLooper->wake();
6578}
6579
Vishnu Nairc519ff72021-01-21 08:23:08 -08006580void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6581 if (changes.oldFocus) {
6582 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006583 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006584 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006585 "focus left window");
6586 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006587 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006588 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006589 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006590 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006591 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006592 }
6593
Prabir Pradhan99987712020-11-10 18:43:05 -08006594 // If a window has pointer capture, then it must have focus. We need to ensure that this
6595 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6596 // If the window loses focus before it loses pointer capture, then the window can be in a state
6597 // where it has pointer capture but not focus, violating the contract. Therefore we must
6598 // dispatch the pointer capture event before the focus event. Since focus events are added to
6599 // the front of the queue (above), we add the pointer capture event to the front of the queue
6600 // after the focus events are added. This ensures the pointer capture event ends up at the
6601 // front.
6602 disablePointerCaptureForcedLocked();
6603
Vishnu Nairc519ff72021-01-21 08:23:08 -08006604 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006605 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006606 }
6607}
Vishnu Nair958da932020-08-21 17:12:37 -07006608
Prabir Pradhan99987712020-11-10 18:43:05 -08006609void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006610 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006611 return;
6612 }
6613
6614 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6615
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006616 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006617 setPointerCaptureLocked(false);
6618 }
6619
6620 if (!mWindowTokenWithPointerCapture) {
6621 // No need to send capture changes because no window has capture.
6622 return;
6623 }
6624
6625 if (mPendingEvent != nullptr) {
6626 // Move the pending event to the front of the queue. This will give the chance
6627 // for the pending event to be dropped if it is a captured event.
6628 mInboundQueue.push_front(mPendingEvent);
6629 mPendingEvent = nullptr;
6630 }
6631
6632 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006633 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006634 mInboundQueue.push_front(std::move(entry));
6635}
6636
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006637void InputDispatcher::setPointerCaptureLocked(bool enable) {
6638 mCurrentPointerCaptureRequest.enable = enable;
6639 mCurrentPointerCaptureRequest.seq++;
6640 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006641 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006642 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006643 };
6644 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006645}
6646
Vishnu Nair599f1412021-06-21 10:39:58 -07006647void InputDispatcher::displayRemoved(int32_t displayId) {
6648 { // acquire lock
6649 std::scoped_lock _l(mLock);
6650 // Set an empty list to remove all handles from the specific display.
6651 setInputWindowsLocked(/* window handles */ {}, displayId);
6652 setFocusedApplicationLocked(displayId, nullptr);
6653 // Call focus resolver to clean up stale requests. This must be called after input windows
6654 // have been removed for the removed display.
6655 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006656 // Reset pointer capture eligibility, regardless of previous state.
6657 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006658 // Remove the associated touch mode state.
6659 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006660 } // release lock
6661
6662 // Wake up poll loop since it may need to make new input dispatching choices.
6663 mLooper->wake();
6664}
6665
Patrick Williamsd828f302023-04-28 17:52:08 -05006666void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006667 // The listener sends the windows as a flattened array. Separate the windows by display for
6668 // more convenient parsing.
6669 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006670 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006671 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006672 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006673 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006674
6675 { // acquire lock
6676 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006677
6678 // Ensure that we have an entry created for all existing displays so that if a displayId has
6679 // no windows, we can tell that the windows were removed from the display.
6680 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6681 handlesPerDisplay[displayId];
6682 }
6683
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006684 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006685 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006686 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6687 }
6688
6689 for (const auto& [displayId, handles] : handlesPerDisplay) {
6690 setInputWindowsLocked(handles, displayId);
6691 }
Patrick Williamsd828f302023-04-28 17:52:08 -05006692
6693 mWindowInfosVsyncId = update.vsyncId;
6694 mWindowInfosTimestamp = update.timestamp;
6695
6696 int64_t delay = systemTime() - update.timestamp;
6697 if (delay > mMaxWindowInfosDelay) {
6698 mMaxWindowInfosDelay = delay;
6699 mMaxWindowInfosDelayVsyncId = update.vsyncId;
6700 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006701 }
6702 // Wake up poll loop since it may need to make new input dispatching choices.
6703 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006704}
6705
Vishnu Nair062a8672021-09-03 16:07:44 -07006706bool InputDispatcher::shouldDropInput(
6707 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006708 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6709 (windowHandle->getInfo()->inputConfig.test(
6710 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006711 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006712 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6713 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006714 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006715 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006716 windowHandle->getInfo()->displayId);
6717 return true;
6718 }
6719 return false;
6720}
6721
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006722void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006723 const gui::WindowInfosUpdate& update) {
6724 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006725}
6726
Arthur Hungdfd528e2021-12-08 13:23:04 +00006727void InputDispatcher::cancelCurrentTouch() {
6728 {
6729 std::scoped_lock _l(mLock);
6730 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006731 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006732 "cancel current touch");
6733 synthesizeCancelationEventsForAllConnectionsLocked(options);
6734
6735 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006736 }
6737 // Wake up poll loop since there might be work to do.
6738 mLooper->wake();
6739}
6740
Prabir Pradhan87112a72023-04-20 19:13:39 +00006741void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006742 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006743
6744 std::scoped_lock _l(mLock);
6745 mConfig = config;
6746}
6747
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006748void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6749 std::scoped_lock _l(mLock);
6750 mMonitorDispatchingTimeout = timeout;
6751}
6752
Arthur Hungc539dbb2022-12-08 07:45:36 +00006753void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6754 const sp<WindowInfoHandle>& oldWindowHandle,
6755 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006756 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006757 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006758 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6759 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006760 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6761 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6762 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6763 newWindowHandle->getInfo()->inputConfig.test(
6764 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6765 const sp<WindowInfoHandle> oldWallpaper =
6766 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6767 const sp<WindowInfoHandle> newWallpaper =
6768 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6769 if (oldWallpaper == newWallpaper) {
6770 return;
6771 }
6772
6773 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006774 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6775 addWindowTargetLocked(oldWallpaper,
6776 oldTouchedWindow.targetFlags |
6777 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6778 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6779 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006780 }
6781
6782 if (newWallpaper != nullptr) {
6783 state.addOrUpdateWindow(newWallpaper,
6784 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6785 InputTarget::Flags::WINDOW_IS_OBSCURED |
6786 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6787 pointerIds);
6788 }
6789}
6790
6791void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6792 ftl::Flags<InputTarget::Flags> newTargetFlags,
6793 const sp<WindowInfoHandle> fromWindowHandle,
6794 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006795 TouchState& state,
6796 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006797 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6798 fromWindowHandle->getInfo()->inputConfig.test(
6799 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6800 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6801 toWindowHandle->getInfo()->inputConfig.test(
6802 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6803
6804 const sp<WindowInfoHandle> oldWallpaper =
6805 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6806 const sp<WindowInfoHandle> newWallpaper =
6807 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6808 if (oldWallpaper == newWallpaper) {
6809 return;
6810 }
6811
6812 if (oldWallpaper != nullptr) {
6813 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6814 "transferring touch focus to another window");
6815 state.removeWindowByToken(oldWallpaper->getToken());
6816 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6817 }
6818
6819 if (newWallpaper != nullptr) {
6820 nsecs_t downTimeInTarget = now();
6821 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6822 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6823 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6824 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6825 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006826 std::shared_ptr<Connection> wallpaperConnection =
6827 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006828 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006829 std::shared_ptr<Connection> toConnection =
6830 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006831 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6832 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6833 wallpaperFlags);
6834 }
6835 }
6836}
6837
6838sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6839 const sp<WindowInfoHandle>& windowHandle) const {
6840 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6841 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6842 bool foundWindow = false;
6843 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6844 if (!foundWindow && otherHandle != windowHandle) {
6845 continue;
6846 }
6847 if (windowHandle == otherHandle) {
6848 foundWindow = true;
6849 continue;
6850 }
6851
6852 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6853 return otherHandle;
6854 }
6855 }
6856 return nullptr;
6857}
6858
Garfield Tane84e6f92019-08-29 17:28:41 -07006859} // namespace android::inputdispatcher