blob: b6a9ac5c753534d7706f8f1f277d09d49fcf3896 [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 Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000035#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010037#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Michael Wright44753b12020-07-08 13:48:11 +010040#include <cerrno>
41#include <cinttypes>
42#include <climits>
43#include <cstddef>
44#include <ctime>
45#include <queue>
46#include <sstream>
47
48#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000049#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070050#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#define INDENT " "
53#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
56
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080057using namespace android::ftl::flag_operators;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -070058using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080059using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000060using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070062using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050063using android::gui::FocusRequest;
64using android::gui::TouchOcclusionMode;
65using android::gui::WindowInfo;
66using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080067using android::os::InputEventInjectionResult;
68using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069
Garfield Tane84e6f92019-08-29 17:28:41 -070070namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Prabir Pradhancef936d2021-07-21 16:17:52 +000072namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000073// Temporarily releases a held mutex for the lifetime of the instance.
74// Named to match std::scoped_lock
75class scoped_unlock {
76public:
77 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
78 ~scoped_unlock() { mMutex.lock(); }
79
80private:
81 std::mutex& mMutex;
82};
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// Default input dispatching timeout if there is no focused application or paused window
85// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080086const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
87 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
88 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for all pending events to be processed when an app switch
91// key is on the way. This is used to preempt input dispatch and drop input events
92// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// 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 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700122inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000123 if (binder == nullptr) {
124 return "<null>";
125 }
126 return StringPrintf("%p", binder.get());
127}
128
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000129inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700130 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
131 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132}
133
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700134Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 case AKEY_EVENT_ACTION_DOWN:
137 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700138 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700140 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 }
142}
143
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700144Result<void> validateKeyEvent(int32_t action) {
145 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146}
147
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700148Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800149 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700150 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700151 case AMOTION_EVENT_ACTION_UP: {
152 if (pointerCount != 1) {
153 return Error() << "invalid pointer count " << pointerCount;
154 }
155 return {};
156 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 case AMOTION_EVENT_ACTION_HOVER_ENTER:
159 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700160 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
161 if (pointerCount < 1) {
162 return Error() << "invalid pointer count " << pointerCount;
163 }
164 return {};
165 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800166 case AMOTION_EVENT_ACTION_CANCEL:
167 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700169 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 case AMOTION_EVENT_ACTION_POINTER_DOWN:
171 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800172 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700173 if (index < 0) {
174 return Error() << "invalid index " << index << " for "
175 << MotionEvent::actionToString(action);
176 }
177 if (index >= pointerCount) {
178 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
179 }
180 if (pointerCount <= 1) {
181 return Error() << "invalid pointer count " << pointerCount << " for "
182 << MotionEvent::actionToString(action);
183 }
184 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 }
186 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700187 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
188 if (actionButton == 0) {
189 return Error() << "action button should be nonzero for "
190 << MotionEvent::actionToString(action);
191 }
192 return {};
193 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700195 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 }
197}
198
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000199int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500200 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
201}
202
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700203Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
204 const PointerProperties* pointerProperties) {
205 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
206 if (!actionCheck.ok()) {
207 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 }
209 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700210 return Error() << "Motion event has invalid pointer count " << pointerCount
211 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800213 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 for (size_t i = 0; i < pointerCount; i++) {
215 int32_t id = pointerProperties[i].id;
216 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700217 return Error() << "Motion event has invalid pointer id " << id
218 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800220 if (pointerIdBits.test(id)) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700221 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800223 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700225 return {};
226}
227
228Result<void> validateInputEvent(const InputEvent& event) {
229 switch (event.getType()) {
230 case InputEventType::KEY: {
231 const KeyEvent& key = static_cast<const KeyEvent&>(event);
232 const int32_t action = key.getAction();
233 return validateKeyEvent(action);
234 }
235 case InputEventType::MOTION: {
236 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
237 const int32_t action = motion.getAction();
238 const size_t pointerCount = motion.getPointerCount();
239 const PointerProperties* pointerProperties = motion.getPointerProperties();
240 const int32_t actionButton = motion.getActionButton();
241 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
242 }
243 default: {
244 return {};
245 }
246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247}
248
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000249std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000251 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 }
253
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000254 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 bool first = true;
256 Region::const_iterator cur = region.begin();
257 Region::const_iterator const tail = region.end();
258 while (cur != tail) {
259 if (first) {
260 first = false;
261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800262 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800264 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 cur++;
266 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000267 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268}
269
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000270std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500271 constexpr size_t maxEntries = 50; // max events to print
272 constexpr size_t skipBegin = maxEntries / 2;
273 const size_t skipEnd = queue.size() - maxEntries / 2;
274 // skip from maxEntries / 2 ... size() - maxEntries/2
275 // only print from 0 .. skipBegin and then from skipEnd .. size()
276
277 std::string dump;
278 for (size_t i = 0; i < queue.size(); i++) {
279 const DispatchEntry& entry = *queue[i];
280 if (i >= skipBegin && i < skipEnd) {
281 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
282 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
283 continue;
284 }
285 dump.append(INDENT4);
286 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800287 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
288 "ms",
289 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500290 ns2ms(currentTime - entry.eventEntry->eventTime));
291 if (entry.deliveryTime != 0) {
292 // This entry was delivered, so add information on how long we've been waiting
293 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
294 }
295 dump.append("\n");
296 }
297 return dump;
298}
299
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700300/**
301 * Find the entry in std::unordered_map by key, and return it.
302 * If the entry is not found, return a default constructed entry.
303 *
304 * Useful when the entries are vectors, since an empty vector will be returned
305 * if the entry is not found.
306 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
307 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700308template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000309V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700310 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700311 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800312}
313
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000314bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700315 if (first == second) {
316 return true;
317 }
318
319 if (first == nullptr || second == nullptr) {
320 return false;
321 }
322
323 return first->getToken() == second->getToken();
324}
325
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000326bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000327 if (first == nullptr || second == nullptr) {
328 return false;
329 }
330 return first->applicationInfo.token != nullptr &&
331 first->applicationInfo.token == second->applicationInfo.token;
332}
333
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800334template <typename T>
335size_t firstMarkedBit(T set) {
336 // TODO: replace with std::countr_zero from <bit> when that's available
337 LOG_ALWAYS_FATAL_IF(set.none());
338 size_t i = 0;
339 while (!set.test(i)) {
340 i++;
341 }
342 return i;
343}
344
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800345std::unique_ptr<DispatchEntry> createDispatchEntry(
346 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
347 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700348 if (inputTarget.useDefaultPointerTransform()) {
349 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700350 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700351 inputTarget.displayTransform,
352 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000353 }
354
355 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
356 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700358 std::vector<PointerCoords> pointerCoords;
359 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360
361 // Use the first pointer information to normalize all other pointers. This could be any pointer
362 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700363 // uses the transform for the normalized pointer.
364 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800365 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700366 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 // Iterate through all pointers in the event to normalize against the first.
369 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
370 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
371 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373
374 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 // First, apply the current pointer's transform to update the coordinates into
376 // window space.
377 pointerCoords[pointerIndex].transform(currTransform);
378 // Next, apply the inverse transform of the normalized coordinates so the
379 // current coordinates are transformed into the normalized coordinate space.
380 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000381 }
382
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700383 std::unique_ptr<MotionEntry> combinedMotionEntry =
384 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
385 motionEntry.deviceId, motionEntry.source,
386 motionEntry.displayId, motionEntry.policyFlags,
387 motionEntry.action, motionEntry.actionButton,
388 motionEntry.flags, motionEntry.metaState,
389 motionEntry.buttonState, motionEntry.classification,
390 motionEntry.edgeFlags, motionEntry.xPrecision,
391 motionEntry.yPrecision, motionEntry.xCursorPosition,
392 motionEntry.yCursorPosition, motionEntry.downTime,
393 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000394 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000395
396 if (motionEntry.injectionState) {
397 combinedMotionEntry->injectionState = motionEntry.injectionState;
398 combinedMotionEntry->injectionState->refCount += 1;
399 }
400
401 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700402 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700403 firstPointerTransform, inputTarget.displayTransform,
404 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000405 return dispatchEntry;
406}
407
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000408status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
409 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700410 std::unique_ptr<InputChannel> uniqueServerChannel;
411 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
412
413 serverChannel = std::move(uniqueServerChannel);
414 return result;
415}
416
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500417template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000418bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500419 if (lhs == nullptr && rhs == nullptr) {
420 return true;
421 }
422 if (lhs == nullptr || rhs == nullptr) {
423 return false;
424 }
425 return *lhs == *rhs;
426}
427
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000428KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000429 KeyEvent event;
430 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
431 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
432 entry.repeatCount, entry.downTime, entry.eventTime);
433 return event;
434}
435
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000437 // Do not keep track of gesture monitors. They receive every event and would disproportionately
438 // affect the statistics.
439 if (connection.monitor) {
440 return false;
441 }
442 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
443 if (!connection.responsive) {
444 return false;
445 }
446 return true;
447}
448
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000449bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000450 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
451 const int32_t& inputEventId = eventEntry.id;
452 if (inputEventId != dispatchEntry.resolvedEventId) {
453 // Event was transmuted
454 return false;
455 }
456 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
457 return false;
458 }
459 // Only track latency for events that originated from hardware
460 if (eventEntry.isSynthesized()) {
461 return false;
462 }
463 const EventEntry::Type& inputEventEntryType = eventEntry.type;
464 if (inputEventEntryType == EventEntry::Type::KEY) {
465 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
466 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
467 return false;
468 }
469 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
470 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
471 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
472 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
473 return false;
474 }
475 } else {
476 // Not a key or a motion
477 return false;
478 }
479 if (!shouldReportMetricsForConnection(connection)) {
480 return false;
481 }
482 return true;
483}
484
Prabir Pradhancef936d2021-07-21 16:17:52 +0000485/**
486 * Connection is responsive if it has no events in the waitQueue that are older than the
487 * current time.
488 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000489bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000490 const nsecs_t currentTime = now();
491 for (const DispatchEntry* entry : connection.waitQueue) {
492 if (entry->timeoutTime < currentTime) {
493 return false;
494 }
495 }
496 return true;
497}
498
Antonio Kantekf16f2832021-09-28 04:39:20 +0000499// Returns true if the event type passed as argument represents a user activity.
500bool isUserActivityEvent(const EventEntry& eventEntry) {
501 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000502 case EventEntry::Type::CONFIGURATION_CHANGED:
503 case EventEntry::Type::DEVICE_RESET:
504 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000505 case EventEntry::Type::FOCUS:
506 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000508 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000509 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000510 case EventEntry::Type::KEY:
511 case EventEntry::Type::MOTION:
512 return true;
513 }
514}
515
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800516// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000517bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000518 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800519 const auto inputConfig = windowInfo.inputConfig;
520 if (windowInfo.displayId != displayId ||
521 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800522 return false;
523 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700524 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800525 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800526 return false;
527 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000528
529 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
530 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
531 // the window. Points on the right and bottom edges should not be inside the window, so we need
532 // to be careful about performing a hit test when the display is rotated, since the "right" and
533 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
534 // logical display in which WM determined the bounds. Perform the hit test in the logical
535 // display space to ensure these edges are considered correctly in all orientations.
536 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
537 const auto p = displayTransform.transform(x, y);
538 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800539 return false;
540 }
541 return true;
542}
543
Prabir Pradhand65552b2021-10-07 11:23:50 -0700544bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
545 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000546 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700547}
548
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800549// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000550// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
551// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
552// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800553// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000554bool canReceiveForegroundTouches(const WindowInfo& info) {
555 // A non-touchable window can still receive touch events (e.g. in the case of
556 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
557 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
558}
559
Antonio Kantek48710e42022-03-24 14:19:30 -0700560bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
561 if (windowHandle == nullptr) {
562 return false;
563 }
564 const WindowInfo* windowInfo = windowHandle->getInfo();
565 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
566 return true;
567 }
568 return false;
569}
570
Prabir Pradhan5735a322022-04-11 17:23:34 +0000571// Checks targeted injection using the window's owner's uid.
572// Returns an empty string if an entry can be sent to the given window, or an error message if the
573// entry is a targeted injection whose uid target doesn't match the window owner.
574std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
575 const EventEntry& entry) {
576 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
577 // The event was not injected, or the injected event does not target a window.
578 return {};
579 }
580 const int32_t uid = *entry.injectionState->targetUid;
581 if (window == nullptr) {
582 return StringPrintf("No valid window target for injection into uid %d.", uid);
583 }
584 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
585 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
586 "owned by uid %d.",
587 uid, window->getName().c_str(), window->getInfo()->ownerUid);
588 }
589 return {};
590}
591
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000592std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700593 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
594 // Always dispatch mouse events to cursor position.
595 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000596 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700597 }
598
599 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000600 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
601 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602}
603
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700604std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
605 if (eventEntry.type == EventEntry::Type::KEY) {
606 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
607 return keyEntry.downTime;
608 } else if (eventEntry.type == EventEntry::Type::MOTION) {
609 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
610 return motionEntry.downTime;
611 }
612 return std::nullopt;
613}
614
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000615/**
616 * Compare the old touch state to the new touch state, and generate the corresponding touched
617 * windows (== input targets).
618 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
619 * If the pointer just entered the new window, produce HOVER_ENTER.
620 * For pointers remaining in the window, produce HOVER_MOVE.
621 */
622std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
623 const TouchState& newTouchState,
624 const MotionEntry& entry) {
625 std::vector<TouchedWindow> out;
626 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
627 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
628 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
629 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
630 // Not a hover event - don't need to do anything
631 return out;
632 }
633
634 // We should consider all hovering pointers here. But for now, just use the first one
635 const int32_t pointerId = entry.pointerProperties[0].id;
636
637 std::set<sp<WindowInfoHandle>> oldWindows;
638 if (oldState != nullptr) {
639 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
640 }
641
642 std::set<sp<WindowInfoHandle>> newWindows =
643 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
644
645 // If the pointer is no longer in the new window set, send HOVER_EXIT.
646 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
647 if (newWindows.find(oldWindow) == newWindows.end()) {
648 TouchedWindow touchedWindow;
649 touchedWindow.windowHandle = oldWindow;
650 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800651 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000652 out.push_back(touchedWindow);
653 }
654 }
655
656 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
657 TouchedWindow touchedWindow;
658 touchedWindow.windowHandle = newWindow;
659 if (oldWindows.find(newWindow) == oldWindows.end()) {
660 // Any windows that have this pointer now, and didn't have it before, should get
661 // HOVER_ENTER
662 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
663 } else {
664 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700665 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
666 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
667 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000668 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
669 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800670 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000671 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
672 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
673 }
674 out.push_back(touchedWindow);
675 }
676 return out;
677}
678
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800679template <typename T>
680std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
681 left.insert(left.end(), right.begin(), right.end());
682 return left;
683}
684
Harry Cuttsb166c002023-05-09 13:06:05 +0000685// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
686// both.
687void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
688 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
689 if (!window.windowHandle->getInfo()->inputConfig.test(
690 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
691 // In addition to TouchState, erase this window from the input targets! We don't have a
692 // good way to do this today except by adding a nested loop.
693 // TODO(b/282025641): simplify this code once InputTargets are being identified
694 // separately from TouchedWindows.
695 std::erase_if(targets, [&](const InputTarget& target) {
696 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
697 });
698 return true;
699 }
700 return false;
701 });
702}
703
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000704} // namespace
705
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706// --- InputDispatcher ---
707
Prabir Pradhana41d2442023-04-20 21:30:40 +0000708InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800709 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
710
Prabir Pradhana41d2442023-04-20 21:30:40 +0000711InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800712 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700713 : mPolicy(policy),
714 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700715 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800716 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700717 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700718 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700719 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800720 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700721 mDispatchEnabled(false),
722 mDispatchFrozen(false),
723 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100724 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000725 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800726 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800727 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000728 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000729 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700730 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800731 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700733 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700734#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700735 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700736#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700737 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738}
739
740InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000741 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742
Prabir Pradhancef936d2021-07-21 16:17:52 +0000743 resetKeyRepeatLocked();
744 releasePendingEventLocked();
745 drainInboundQueueLocked();
746 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000748 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700749 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000750 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 }
752}
753
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700754status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700755 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700756 return ALREADY_EXISTS;
757 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700758 mThread = std::make_unique<InputThread>(
759 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
760 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700761}
762
763status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700764 if (mThread && mThread->isCallingThread()) {
765 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700766 return INVALID_OPERATION;
767 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700768 mThread.reset();
769 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700770}
771
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700773 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800775 std::scoped_lock _l(mLock);
776 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777
778 // Run a dispatch loop if there are no pending commands.
779 // The dispatch loop might enqueue commands to run afterwards.
780 if (!haveCommandsLocked()) {
781 dispatchOnceInnerLocked(&nextWakeupTime);
782 }
783
784 // Run all pending commands if there are any.
785 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000786 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700787 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800789
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700790 // If we are still waiting for ack on some events,
791 // we might have to wake up earlier to check if an app is anr'ing.
792 const nsecs_t nextAnrCheck = processAnrsLocked();
793 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
794
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800795 // We are about to enter an infinitely long sleep, because we have no commands or
796 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700797 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800798 mDispatcherEnteredIdle.notify_all();
799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 } // release lock
801
802 // Wait for callback or timeout or wake. (make sure we round up, not down)
803 nsecs_t currentTime = now();
804 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
805 mLooper->pollOnce(timeoutMillis);
806}
807
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700808/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500809 * Raise ANR if there is no focused window.
810 * Before the ANR is raised, do a final state check:
811 * 1. The currently focused application must be the same one we are waiting for.
812 * 2. Ensure we still don't have a focused window.
813 */
814void InputDispatcher::processNoFocusedWindowAnrLocked() {
815 // Check if the application that we are waiting for is still focused.
816 std::shared_ptr<InputApplicationHandle> focusedApplication =
817 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
818 if (focusedApplication == nullptr ||
819 focusedApplication->getApplicationToken() !=
820 mAwaitedFocusedApplication->getApplicationToken()) {
821 // Unexpected because we should have reset the ANR timer when focused application changed
822 ALOGE("Waited for a focused window, but focused application has already changed to %s",
823 focusedApplication->getName().c_str());
824 return; // The focused application has changed.
825 }
826
chaviw98318de2021-05-19 16:45:23 -0500827 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500828 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
829 if (focusedWindowHandle != nullptr) {
830 return; // We now have a focused window. No need for ANR.
831 }
832 onAnrLocked(mAwaitedFocusedApplication);
833}
834
835/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700836 * Check if any of the connections' wait queues have events that are too old.
837 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
838 * Return the time at which we should wake up next.
839 */
840nsecs_t InputDispatcher::processAnrsLocked() {
841 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700842 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
844 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
845 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500846 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700847 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500848 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700849 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700850 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500851 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700852 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
853 }
854 }
855
856 // Check if any connection ANRs are due
857 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
858 if (currentTime < nextAnrCheck) { // most likely scenario
859 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
860 }
861
862 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700863 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700864 if (connection == nullptr) {
865 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
866 return nextAnrCheck;
867 }
868 connection->responsive = false;
869 // Stop waking up for this unresponsive connection
870 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000871 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700872 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700873}
874
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800875std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700876 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800877 if (connection->monitor) {
878 return mMonitorDispatchingTimeout;
879 }
880 const sp<WindowInfoHandle> window =
881 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700882 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500883 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700884 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500885 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886}
887
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
889 nsecs_t currentTime = now();
890
Jeff Browndc5992e2014-04-11 01:27:26 -0700891 // Reset the key repeat timer whenever normal dispatch is suspended while the
892 // device is in a non-interactive state. This is to ensure that we abort a key
893 // repeat if the device is just coming out of sleep.
894 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 resetKeyRepeatLocked();
896 }
897
898 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
899 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100900 if (DEBUG_FOCUS) {
901 ALOGD("Dispatch frozen. Waiting some more.");
902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 return;
904 }
905
906 // Optimize latency of app switches.
907 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
908 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
909 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
910 if (mAppSwitchDueTime < *nextWakeupTime) {
911 *nextWakeupTime = mAppSwitchDueTime;
912 }
913
914 // Ready to start a new event.
915 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700917 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 if (isAppSwitchDue) {
919 // The inbound queue is empty so the app switch key we were waiting
920 // for will never arrive. Stop waiting for it.
921 resetPendingAppSwitchLocked(false);
922 isAppSwitchDue = false;
923 }
924
925 // Synthesize a key repeat if appropriate.
926 if (mKeyRepeatState.lastKeyEntry) {
927 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
928 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
929 } else {
930 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
931 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
932 }
933 }
934 }
935
936 // Nothing to do if there is no pending event.
937 if (!mPendingEvent) {
938 return;
939 }
940 } else {
941 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700942 mPendingEvent = mInboundQueue.front();
943 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 traceInboundQueueLengthLocked();
945 }
946
947 // Poke user activity for this event.
948 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700949 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 }
952
953 // Now we have an event to dispatch.
954 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700955 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700957 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700959 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700961 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 }
963
964 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700965 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967
968 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700969 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700970 const ConfigurationChangedEntry& typedEntry =
971 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700973 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700974 break;
975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700977 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 const DeviceResetEntry& typedEntry =
979 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700981 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 break;
983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100985 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700986 std::shared_ptr<FocusEntry> typedEntry =
987 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100988 dispatchFocusLocked(currentTime, typedEntry);
989 done = true;
990 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
991 break;
992 }
993
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700994 case EventEntry::Type::TOUCH_MODE_CHANGED: {
995 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
996 dispatchTouchModeChangeLocked(currentTime, typedEntry);
997 done = true;
998 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
999 break;
1000 }
1001
Prabir Pradhan99987712020-11-10 18:43:05 -08001002 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1003 const auto typedEntry =
1004 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1005 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1006 done = true;
1007 break;
1008 }
1009
arthurhungb89ccb02020-12-30 16:19:01 +08001010 case EventEntry::Type::DRAG: {
1011 std::shared_ptr<DragEntry> typedEntry =
1012 std::static_pointer_cast<DragEntry>(mPendingEvent);
1013 dispatchDragLocked(currentTime, typedEntry);
1014 done = true;
1015 break;
1016 }
1017
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001019 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001021 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 resetPendingAppSwitchLocked(true);
1023 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001024 } else if (dropReason == DropReason::NOT_DROPPED) {
1025 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 }
1027 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1032 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 break;
1036 }
1037
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001038 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001039 std::shared_ptr<MotionEntry> motionEntry =
1040 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001041 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1042 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001044 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001045 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001047 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1048 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001049 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001050 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Chris Yef59a2f42020-10-16 12:55:26 -07001053
1054 case EventEntry::Type::SENSOR: {
1055 std::shared_ptr<SensorEntry> sensorEntry =
1056 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1057 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1058 dropReason = DropReason::APP_SWITCH;
1059 }
1060 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1061 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1062 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1063 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1064 dropReason = DropReason::STALE;
1065 }
1066 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1067 done = true;
1068 break;
1069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
1071
1072 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001073 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001074 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
Michael Wright3a981722015-06-10 15:26:13 +01001076 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077
1078 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001079 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
1081}
1082
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001083bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1084 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1085}
1086
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001087/**
1088 * Return true if the events preceding this incoming motion event should be dropped
1089 * Return false otherwise (the default behaviour)
1090 */
1091bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001092 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001093 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001094
1095 // Optimize case where the current application is unresponsive and the user
1096 // decides to touch a window in a different application.
1097 // If the application takes too long to catch up then we drop all events preceding
1098 // the touch into the other window.
1099 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001100 const int32_t displayId = motionEntry.displayId;
1101 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001102 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001103
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001104 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001105 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001106 touchedWindowHandle->getApplicationToken() !=
1107 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001108 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001109 ALOGI("Pruning input queue because user touched a different application while waiting "
1110 "for %s",
1111 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001112 return true;
1113 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001114
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001115 // Alternatively, maybe there's a spy window that could handle this event.
1116 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1117 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1118 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001119 const std::shared_ptr<Connection> connection =
1120 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001121 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001122 // This spy window could take more input. Drop all events preceding this
1123 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001124 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001125 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001126 mAwaitedFocusedApplication->getName().c_str());
1127 return true;
1128 }
1129 }
1130 }
1131
1132 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1133 // yet been processed by some connections, the dispatcher will wait for these motion
1134 // events to be processed before dispatching the key event. This is because these motion events
1135 // may cause a new window to be launched, which the user might expect to receive focus.
1136 // To prevent waiting forever for such events, just send the key to the currently focused window
1137 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1138 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1139 "just send the pending key event to the focused window.");
1140 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001141 }
1142 return false;
1143}
1144
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001145bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001146 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001147 mInboundQueue.push_back(std::move(newEntry));
1148 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 traceInboundQueueLengthLocked();
1150
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001151 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001153 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1154 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 // Optimize app switch latency.
1156 // If the application takes too long to catch up then we drop all events preceding
1157 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001158 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001160 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001162 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001164 if (DEBUG_APP_SWITCH) {
1165 ALOGD("App switch is pending!");
1166 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 mAppSwitchSawKeyDown = false;
1169 needWake = true;
1170 }
1171 }
1172 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001173
1174 // If a new up event comes in, and the pending event with same key code has been asked
1175 // to try again later because of the policy. We have to reset the intercept key wake up
1176 // time for it may have been handled in the policy and could be dropped.
1177 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1178 mPendingEvent->type == EventEntry::Type::KEY) {
1179 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1180 if (pendingKey.keyCode == keyEntry.keyCode &&
1181 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001182 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1183 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001184 pendingKey.interceptKeyWakeupTime = 0;
1185 needWake = true;
1186 }
1187 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 break;
1189 }
1190
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001191 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001192 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1193 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1195 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001196 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001200 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001201 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1202 break;
1203 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001204 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001205 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001206 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001207 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001208 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1209 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001210 // nothing to do
1211 break;
1212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214
1215 return needWake;
1216}
1217
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001218void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001219 // Do not store sensor event in recent queue to avoid flooding the queue.
1220 if (entry->type != EventEntry::Type::SENSOR) {
1221 mRecentQueue.push_back(entry);
1222 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001223 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001224 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 }
1226}
1227
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001228std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001229InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001230 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001232 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001233 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001234 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001235 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001236 continue;
1237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001239 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001240 if (!info.isSpy() &&
1241 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001242 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001243 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001244
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001245 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1246 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001247 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001248 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
1250 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001251 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252}
1253
Prabir Pradhand65552b2021-10-07 11:23:50 -07001254std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001255 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001256 // Traverse windows from front to back and gather the touched spy windows.
1257 std::vector<sp<WindowInfoHandle>> spyWindows;
1258 const auto& windowHandles = getWindowHandlesLocked(displayId);
1259 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1260 const WindowInfo& info = *windowHandle->getInfo();
1261
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001262 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001263 continue;
1264 }
1265 if (!info.isSpy()) {
1266 // The first touched non-spy window was found, so return the spy windows touched so far.
1267 return spyWindows;
1268 }
1269 spyWindows.push_back(windowHandle);
1270 }
1271 return spyWindows;
1272}
1273
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001274void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 const char* reason;
1276 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001277 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001278 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001279 ALOGD("Dropped event because policy consumed it.");
1280 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 reason = "inbound event was dropped because the policy consumed it";
1282 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001283 case DropReason::DISABLED:
1284 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285 ALOGI("Dropped event because input dispatch is disabled.");
1286 }
1287 reason = "inbound event was dropped because input dispatch is disabled";
1288 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001289 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 ALOGI("Dropped event because of pending overdue app switch.");
1291 reason = "inbound event was dropped because of pending overdue app switch";
1292 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001293 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 ALOGI("Dropped event because the current application is not responding and the user "
1295 "has started interacting with a different application.");
1296 reason = "inbound event was dropped because the current application is not responding "
1297 "and the user has started interacting with a different application";
1298 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001299 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 ALOGI("Dropped event because it is stale.");
1301 reason = "inbound event was dropped because it is stale";
1302 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001303 case DropReason::NO_POINTER_CAPTURE:
1304 ALOGI("Dropped event because there is no window with Pointer Capture.");
1305 reason = "inbound event was dropped because there is no window with Pointer Capture";
1306 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001307 case DropReason::NOT_DROPPED: {
1308 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 }
1312
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001313 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001314 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001315 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001319 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001320 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1321 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001322 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 synthesizeCancelationEventsForAllConnectionsLocked(options);
1324 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001325 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1326 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 synthesizeCancelationEventsForAllConnectionsLocked(options);
1328 }
1329 break;
1330 }
Chris Yef59a2f42020-10-16 12:55:26 -07001331 case EventEntry::Type::SENSOR: {
1332 break;
1333 }
arthurhungb89ccb02020-12-30 16:19:01 +08001334 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1335 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 break;
1337 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001338 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001339 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001340 case EventEntry::Type::CONFIGURATION_CHANGED:
1341 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001342 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001343 break;
1344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346}
1347
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001348static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1350 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351}
1352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001353bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1354 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1355 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1356 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357}
1358
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001359bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001360 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361}
1362
1363void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001364 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001366 if (DEBUG_APP_SWITCH) {
1367 if (handled) {
1368 ALOGD("App switch has arrived.");
1369 } else {
1370 ALOGD("App switch was abandoned.");
1371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373}
1374
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001376 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377}
1378
Prabir Pradhancef936d2021-07-21 16:17:52 +00001379bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001380 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 return false;
1382 }
1383
1384 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001385 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001386 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001387 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1388 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001389 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 return true;
1391}
1392
Prabir Pradhancef936d2021-07-21 16:17:52 +00001393void InputDispatcher::postCommandLocked(Command&& command) {
1394 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395}
1396
1397void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001398 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001399 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001400 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 releaseInboundEventLocked(entry);
1402 }
1403 traceInboundQueueLengthLocked();
1404}
1405
1406void InputDispatcher::releasePendingEventLocked() {
1407 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001409 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411}
1412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001413void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001415 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001416 if (DEBUG_DISPATCH_CYCLE) {
1417 ALOGD("Injected inbound event was dropped.");
1418 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 }
1421 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001422 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425}
1426
1427void InputDispatcher::resetKeyRepeatLocked() {
1428 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001429 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431}
1432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1434 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435
Michael Wright2e732952014-09-24 13:26:59 -07001436 uint32_t policyFlags = entry->policyFlags &
1437 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001439 std::shared_ptr<KeyEntry> newEntry =
1440 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1441 entry->source, entry->displayId, policyFlags, entry->action,
1442 entry->flags, entry->keyCode, entry->scanCode,
1443 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001445 newEntry->syntheticRepeat = true;
1446 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001448 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449}
1450
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001453 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1454 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456
1457 // Reset key repeating in case a keyboard device was added or removed or something.
1458 resetKeyRepeatLocked();
1459
1460 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001461 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1462 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001463 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001464 };
1465 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 return true;
1467}
1468
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001469bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1470 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001471 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1472 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1473 entry.deviceId);
1474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475
liushenxiang42232912021-05-21 20:24:09 +08001476 // Reset key repeating in case a keyboard device was disabled or enabled.
1477 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1478 resetKeyRepeatLocked();
1479 }
1480
Michael Wrightfb04fd52022-11-24 22:31:11 +00001481 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001484
1485 // Remove all active pointers from this device
1486 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1487 touchState.removeAllPointersForDevice(entry.deviceId);
1488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 return true;
1490}
1491
Vishnu Nairad321cd2020-08-20 16:40:21 -07001492void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001493 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001494 if (mPendingEvent != nullptr) {
1495 // Move the pending event to the front of the queue. This will give the chance
1496 // for the pending event to get dispatched to the newly focused window
1497 mInboundQueue.push_front(mPendingEvent);
1498 mPendingEvent = nullptr;
1499 }
1500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501 std::unique_ptr<FocusEntry> focusEntry =
1502 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1503 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001504
1505 // This event should go to the front of the queue, but behind all other focus events
1506 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001507 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001508 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001509 [](const std::shared_ptr<EventEntry>& event) {
1510 return event->type == EventEntry::Type::FOCUS;
1511 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001512
1513 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001515}
1516
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001517void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001518 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001519 if (channel == nullptr) {
1520 return; // Window has gone away
1521 }
1522 InputTarget target;
1523 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001524 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001525 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001526 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1527 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001528 std::string reason = std::string("reason=").append(entry->reason);
1529 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001530 dispatchEventLocked(currentTime, entry, {target});
1531}
1532
Prabir Pradhan99987712020-11-10 18:43:05 -08001533void InputDispatcher::dispatchPointerCaptureChangedLocked(
1534 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1535 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001536 dropReason = DropReason::NOT_DROPPED;
1537
Prabir Pradhan99987712020-11-10 18:43:05 -08001538 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001539 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001540
1541 if (entry->pointerCaptureRequest.enable) {
1542 // Enable Pointer Capture.
1543 if (haveWindowWithPointerCapture &&
1544 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001545 // This can happen if pointer capture is disabled and re-enabled before we notify the
1546 // app of the state change, so there is no need to notify the app.
1547 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1548 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001549 }
1550 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001551 // This can happen if a window requests capture and immediately releases capture.
1552 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001554 return;
1555 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001556 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1557 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1558 return;
1559 }
1560
Vishnu Nairc519ff72021-01-21 08:23:08 -08001561 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001562 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1563 mWindowTokenWithPointerCapture = token;
1564 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001565 // Disable Pointer Capture.
1566 // We do not check if the sequence number matches for requests to disable Pointer Capture
1567 // for two reasons:
1568 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1569 // to disable capture with the same sequence number: one generated by
1570 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1571 // Capture being disabled in InputReader.
1572 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1573 // actual Pointer Capture state that affects events being generated by input devices is
1574 // in InputReader.
1575 if (!haveWindowWithPointerCapture) {
1576 // Pointer capture was already forcefully disabled because of focus change.
1577 dropReason = DropReason::NOT_DROPPED;
1578 return;
1579 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001580 token = mWindowTokenWithPointerCapture;
1581 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001582 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001583 setPointerCaptureLocked(false);
1584 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001585 }
1586
1587 auto channel = getInputChannelLocked(token);
1588 if (channel == nullptr) {
1589 // Window has gone away, clean up Pointer Capture state.
1590 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001591 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001592 setPointerCaptureLocked(false);
1593 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001594 return;
1595 }
1596 InputTarget target;
1597 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001598 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001599 entry->dispatchInProgress = true;
1600 dispatchEventLocked(currentTime, entry, {target});
1601
1602 dropReason = DropReason::NOT_DROPPED;
1603}
1604
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001605void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1606 const std::shared_ptr<TouchModeEntry>& entry) {
1607 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001608 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001609 if (windowHandles.empty()) {
1610 return;
1611 }
1612 const std::vector<InputTarget> inputTargets =
1613 getInputTargetsFromWindowHandlesLocked(windowHandles);
1614 if (inputTargets.empty()) {
1615 return;
1616 }
1617 entry->dispatchInProgress = true;
1618 dispatchEventLocked(currentTime, entry, inputTargets);
1619}
1620
1621std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1622 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1623 std::vector<InputTarget> inputTargets;
1624 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001625 const sp<IBinder>& token = handle->getToken();
1626 if (token == nullptr) {
1627 continue;
1628 }
1629 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1630 if (channel == nullptr) {
1631 continue; // Window has gone away
1632 }
1633 InputTarget target;
1634 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001635 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001636 inputTargets.push_back(target);
1637 }
1638 return inputTargets;
1639}
1640
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 if (!entry->dispatchInProgress) {
1645 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1646 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1647 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1648 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001649 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 // We have seen two identical key downs in a row which indicates that the device
1651 // driver is automatically generating key repeats itself. We take note of the
1652 // repeat here, but we disable our own next key repeat timer since it is clear that
1653 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001654 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1655 // Make sure we don't get key down from a different device. If a different
1656 // device Id has same key pressed down, the new device Id will replace the
1657 // current one to hold the key repeat with repeat count reset.
1658 // In the future when got a KEY_UP on the device id, drop it and do not
1659 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1661 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001662 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 } else {
1664 // Not a repeat. Save key down state in case we do see a repeat later.
1665 resetKeyRepeatLocked();
1666 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1667 }
1668 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001669 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1670 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001671 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001672 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001673 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1674 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 resetKeyRepeatLocked();
1677 }
1678
1679 if (entry->repeatCount == 1) {
1680 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1681 } else {
1682 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1683 }
1684
1685 entry->dispatchInProgress = true;
1686
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001687 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 }
1689
1690 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001691 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 if (currentTime < entry->interceptKeyWakeupTime) {
1693 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1694 *nextWakeupTime = entry->interceptKeyWakeupTime;
1695 }
1696 return false; // wait until next wakeup
1697 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001698 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 entry->interceptKeyWakeupTime = 0;
1700 }
1701
1702 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001703 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001705 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001706 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001707
1708 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1709 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1710 };
1711 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001712 // Poke user activity for keys not passed to user
1713 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 return false; // wait for the command to run
1715 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001716 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001718 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001719 if (*dropReason == DropReason::NOT_DROPPED) {
1720 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 }
1722 }
1723
1724 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001725 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001726 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001727 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1728 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001729 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001730 // Poke user activity for undispatched keys
1731 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 return true;
1733 }
1734
1735 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001736 InputEventInjectionResult injectionResult;
1737 sp<WindowInfoHandle> focusedWindow =
1738 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1739 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 return false;
1742 }
1743
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001744 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 return true;
1747 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001748 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1749
1750 std::vector<InputTarget> inputTargets;
1751 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001752 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001753 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001755 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001756 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757
1758 // Dispatch the key.
1759 dispatchEventLocked(currentTime, entry, inputTargets);
1760 return true;
1761}
1762
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001764 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1765 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1766 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1767 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1768 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1769 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1770 entry.metaState, entry.repeatCount, entry.downTime);
1771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772}
1773
Prabir Pradhancef936d2021-07-21 16:17:52 +00001774void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1775 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001776 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001777 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1778 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1779 "source=0x%x, sensorType=%s",
1780 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001781 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001782 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001783 auto command = [this, entry]() REQUIRES(mLock) {
1784 scoped_unlock unlock(mLock);
1785
1786 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001787 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001788 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001789 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1790 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001791 };
1792 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001793}
1794
1795bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001796 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1797 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001798 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001799 }
Chris Yef59a2f42020-10-16 12:55:26 -07001800 { // acquire lock
1801 std::scoped_lock _l(mLock);
1802
1803 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1804 std::shared_ptr<EventEntry> entry = *it;
1805 if (entry->type == EventEntry::Type::SENSOR) {
1806 it = mInboundQueue.erase(it);
1807 releaseInboundEventLocked(entry);
1808 }
1809 }
1810 }
1811 return true;
1812}
1813
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001814bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001815 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001816 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001818 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 entry->dispatchInProgress = true;
1820
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001821 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
1823
1824 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001825 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001826 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1828 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 return true;
1830 }
1831
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001832 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833
1834 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001835 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836
1837 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001838 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 if (isPointerEvent) {
1840 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001841
1842 if (mDragState &&
1843 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1844 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1845 pilferPointersLocked(mDragState->dragWindow->getToken());
1846 }
1847
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001848 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001849 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001850 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001851 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1852 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 } else {
1854 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001855 sp<WindowInfoHandle> focusedWindow =
1856 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1857 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1858 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1859 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001860 InputTarget::Flags::FOREGROUND |
1861 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001862 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001865 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 return false;
1867 }
1868
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001869 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001870 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001871 return true;
1872 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001873 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001874 CancelationOptions::Mode mode(
1875 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1876 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001877 CancelationOptions options(mode, "input event injection failed");
1878 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 return true;
1880 }
1881
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001882 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001883 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884
1885 // Dispatch the motion.
1886 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001887 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001888 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 synthesizeCancelationEventsForAllConnectionsLocked(options);
1890 }
1891 dispatchEventLocked(currentTime, entry, inputTargets);
1892 return true;
1893}
1894
chaviw98318de2021-05-19 16:45:23 -05001895void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001896 bool isExiting, const int32_t rawX,
1897 const int32_t rawY) {
1898 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001899 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001900 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1901 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001902
1903 enqueueInboundEventLocked(std::move(dragEntry));
1904}
1905
1906void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1907 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1908 if (channel == nullptr) {
1909 return; // Window has gone away
1910 }
1911 InputTarget target;
1912 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001913 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001914 entry->dispatchInProgress = true;
1915 dispatchEventLocked(currentTime, entry, {target});
1916}
1917
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001918void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001919 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001920 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001921 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001922 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001923 "metaState=0x%x, buttonState=0x%x,"
1924 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001925 prefix, entry.eventTime, entry.deviceId,
1926 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1927 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1928 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1929 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001931 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001932 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001933 "x=%f, y=%f, pressure=%f, size=%f, "
1934 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1935 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001936 i, entry.pointerProperties[i].id,
1937 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1939 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1940 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1941 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1942 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1943 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949}
1950
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001951void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1952 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001953 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001954 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001955 if (DEBUG_DISPATCH_CYCLE) {
1956 ALOGD("dispatchEventToCurrentInputTargets");
1957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001959 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001960
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001963 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001965 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001966 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001967 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001968 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001969 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001971 if (DEBUG_FOCUS) {
1972 ALOGD("Dropping event delivery to target with channel '%s' because it "
1973 "is no longer registered with the input dispatcher.",
1974 inputTarget.inputChannel->getName().c_str());
1975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977 }
1978}
1979
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001980void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001981 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1982 // If the policy decides to close the app, we will get a channel removal event via
1983 // unregisterInputChannel, and will clean up the connection that way. We are already not
1984 // sending new pointers to the connection when it blocked, but focused events will continue to
1985 // pile up.
1986 ALOGW("Canceling events for %s because it is unresponsive",
1987 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001988 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001989 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001990 "application not responding");
1991 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
1993}
1994
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001996 if (DEBUG_FOCUS) {
1997 ALOGD("Resetting ANR timeouts.");
1998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
2000 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002002 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003}
2004
Tiger Huang721e26f2018-07-24 22:26:19 +08002005/**
2006 * Get the display id that the given event should go to. If this event specifies a valid display id,
2007 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2008 * Focused display is the display that the user most recently interacted with.
2009 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002010int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002011 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002012 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002013 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002014 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2015 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016 break;
2017 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002018 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2020 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 break;
2022 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002023 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002024 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002025 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002026 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002027 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002028 case EventEntry::Type::SENSOR:
2029 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002030 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002031 return ADISPLAY_ID_NONE;
2032 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002033 }
2034 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2035}
2036
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002037bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2038 const char* focusedWindowName) {
2039 if (mAnrTracker.empty()) {
2040 // already processed all events that we waited for
2041 mKeyIsWaitingForEventsTimeout = std::nullopt;
2042 return false;
2043 }
2044
2045 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2046 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002047 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002048 mKeyIsWaitingForEventsTimeout = currentTime +
2049 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2050 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002051 return true;
2052 }
2053
2054 // We still have pending events, and already started the timer
2055 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2056 return true; // Still waiting
2057 }
2058
2059 // Waited too long, and some connection still hasn't processed all motions
2060 // Just send the key to the focused window
2061 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2062 focusedWindowName);
2063 mKeyIsWaitingForEventsTimeout = std::nullopt;
2064 return false;
2065}
2066
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002067sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2068 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2069 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002070 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072
Tiger Huang721e26f2018-07-24 22:26:19 +08002073 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002074 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002075 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002076 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2077
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 // If there is no currently focused window and no focused application
2079 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002080 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2081 ALOGI("Dropping %s event because there is no focused window or focused application in "
2082 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002083 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002084 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
2086
Vishnu Nair062a8672021-09-03 16:07:44 -07002087 // Drop key events if requested by input feature
2088 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002089 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002090 }
2091
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2093 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2094 // start interacting with another application via touch (app switch). This code can be removed
2095 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2096 // an app is expected to have a focused window.
2097 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2098 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2099 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002100 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2101 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2102 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002103 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002104 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105 ALOGW("Waiting because no window has focus but %s may eventually add a "
2106 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002107 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002108 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002109 outInjectionResult = InputEventInjectionResult::PENDING;
2110 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2112 // Already raised ANR. Drop the event
2113 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002114 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002115 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 } else {
2117 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002118 outInjectionResult = InputEventInjectionResult::PENDING;
2119 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 }
2121 }
2122
2123 // we have a valid, non-null focused window
2124 resetNoFocusedWindowTimeoutLocked();
2125
Prabir Pradhan5735a322022-04-11 17:23:34 +00002126 // Verify targeted injection.
2127 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2128 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002129 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2130 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 }
2132
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002133 if (focusedWindowHandle->getInfo()->inputConfig.test(
2134 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002135 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002136 outInjectionResult = InputEventInjectionResult::PENDING;
2137 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002138 }
2139
2140 // If the event is a key event, then we must wait for all previous events to
2141 // complete before delivering it because previous events may have the
2142 // side-effect of transferring focus to a different window and we want to
2143 // ensure that the following keys are sent to the new window.
2144 //
2145 // Suppose the user touches a button in a window then immediately presses "A".
2146 // If the button causes a pop-up window to appear then we want to ensure that
2147 // the "A" key is delivered to the new pop-up window. This is because users
2148 // often anticipate pending UI changes when typing on a keyboard.
2149 // To obtain this behavior, we must serialize key events with respect to all
2150 // prior input events.
2151 if (entry.type == EventEntry::Type::KEY) {
2152 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2153 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002154 outInjectionResult = InputEventInjectionResult::PENDING;
2155 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
2158
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2160 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161}
2162
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163/**
2164 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2165 * that are currently unresponsive.
2166 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002167std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2168 const std::vector<Monitor>& monitors) const {
2169 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002171 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002172 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002173 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 if (connection == nullptr) {
2175 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002176 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177 return false;
2178 }
2179 if (!connection->responsive) {
2180 ALOGW("Unresponsive monitor %s will not get the new gesture",
2181 connection->inputChannel->getName().c_str());
2182 return false;
2183 }
2184 return true;
2185 });
2186 return responsiveMonitors;
2187}
2188
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002189/**
2190 * In general, touch should be always split between windows. Some exceptions:
2191 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2192 * from the same device, *and* the window that's receiving the current pointer does not support
2193 * split touch.
2194 * 2. Don't split mouse events
2195 */
2196bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2197 const MotionEntry& entry) const {
2198 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2199 // We should never split mouse events
2200 return false;
2201 }
2202 for (const TouchedWindow& touchedWindow : touchState.windows) {
2203 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2204 // Spy windows should not affect whether or not touch is split.
2205 continue;
2206 }
2207 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2208 continue;
2209 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002210 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2211 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2212 // Wallpaper window should not affect whether or not touch is split
2213 continue;
2214 }
2215
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002216 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2217 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002218 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002219 return false;
2220 }
2221 }
2222 return true;
2223}
2224
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002225std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002226 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2227 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002228 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002230 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 // For security reasons, we defer updating the touch state until we are sure that
2232 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233 const int32_t displayId = entry.displayId;
2234 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002235 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236
2237 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002238 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002240 // Copy current touch state into tempTouchState.
2241 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2242 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002243 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002244 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002245 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2246 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002247 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002248 }
2249
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002250 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002251 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002252 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002253
2254 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2255 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2256 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002257 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2258 // touchable windows.
2259 const bool wasDown = oldState != nullptr && oldState->isDown();
2260 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2261 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002262 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2263 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2264 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002265 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002266
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002267 // If pointers are already down, let's finish the current gesture and ignore the new events
2268 // from another device. However, if the new event is a down event, let's cancel the current
2269 // touch and let the new one take over.
2270 if (switchedDevice && wasDown && !isDown) {
2271 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2272 << " is already down in display " << displayId << ": " << entry.getDescription();
2273 // TODO(b/211379801): test multiple simultaneous input streams.
2274 outInjectionResult = InputEventInjectionResult::FAILED;
2275 return {}; // wrong device
2276 }
2277
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002279 // If a new gesture is starting, clear the touch state completely.
2280 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 tempTouchState.deviceId = entry.deviceId;
2282 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002284 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002285 ALOGI("Dropping move event because a pointer for a different device is already active "
2286 "in display %" PRId32,
2287 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002288 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002289 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002290 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
2292
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002293 if (isHoverAction) {
2294 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2295 // all of the existing hovering pointers and recompute.
2296 tempTouchState.clearHoveringPointers();
2297 }
2298
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2300 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002301 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002302 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002303 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2304 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002305 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002306 auto [newTouchedWindowHandle, outsideTargets] =
2307 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002308
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002309 if (isDown) {
2310 targets += outsideTargets;
2311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002313 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002314 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002316 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002317 }
2318
Prabir Pradhan5735a322022-04-11 17:23:34 +00002319 // Verify targeted injection.
2320 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2321 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002322 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002323 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002324 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002325 }
2326
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002327 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002328 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2330 // New window supports splitting, but we should never split mouse events.
2331 isSplit = !isFromMouse;
2332 } else if (isSplit) {
2333 // New window does not support splitting but we have already split events.
2334 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002335 newTouchedWindowHandle = nullptr;
2336 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002337 } else {
2338 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002339 // be delivered to a new window which supports split touch. Pointers from a mouse device
2340 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002341 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 }
2343
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002344 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002345 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002346 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002347 // Process the foreground window first so that it is the first to receive the event.
2348 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002349 }
2350
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002351 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002352 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2353 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002354 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002355 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002356 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002357 }
2358
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002359 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002360 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002361 continue;
2362 }
2363
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002364 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2365 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002366 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002367 // The "windowHandle" is the target of this hovering pointer.
2368 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002369 }
2370
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002371 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002372 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002374 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2375 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002376 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002377 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378
2379 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002380 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002381 }
2382 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002383 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002385 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002387
2388 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002389 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002390 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002391 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002392 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002394 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2395 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2396
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002397 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2398 // still add a window to the touch state. We should avoid doing that, but some of the
2399 // later checks ("at least one foreground window") rely on this in order to dispatch
2400 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002401 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002402 isDownOrPointerDown
2403 ? std::make_optional(entry.eventTime)
2404 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002405
2406 // If this is the pointer going down and the touched window has a wallpaper
2407 // then also add the touched wallpaper windows so they are locked in for the duration
2408 // of the touch gesture.
2409 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2410 // engine only supports touch events. We would need to add a mechanism similar
2411 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002412 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002413 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2414 windowHandle->getInfo()->inputConfig.test(
2415 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2416 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2417 if (wallpaper != nullptr) {
2418 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2419 InputTarget::Flags::WINDOW_IS_OBSCURED |
2420 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2421 InputTarget::Flags::DISPATCH_AS_IS;
2422 if (isSplit) {
2423 wallpaperFlags |= InputTarget::Flags::SPLIT;
2424 }
2425 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2426 entry.eventTime);
2427 }
2428 }
2429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002431
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002432 // If a window is already pilfering some pointers, give it this new pointer as well and
2433 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2434 // which is a specific behaviour that we want.
2435 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2436 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002437 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002438 touchedWindow.pilferedPointerIds.count() > 0) {
2439 // This window is already pilfering some pointers, and this new pointer is also
2440 // going to it. Therefore, take over this pointer and don't give it to anyone
2441 // else.
2442 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002443 }
2444 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002445
2446 // Restrict all pilfered pointers to the pilfering windows.
2447 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 } else {
2449 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2450
2451 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002452 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002453 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2454 "dropped the pointer down event in display "
2455 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002456 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002457 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
2459
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002460 // If the pointer is not currently hovering, then ignore the event.
2461 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2462 const int32_t pointerId = entry.pointerProperties[0].id;
2463 if (oldState == nullptr ||
2464 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2465 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2466 "display "
2467 << displayId << ": " << entry.getDescription();
2468 outInjectionResult = InputEventInjectionResult::FAILED;
2469 return {};
2470 }
2471 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2472 }
2473
arthurhung6d4bed92021-03-17 11:59:33 +08002474 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002475
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002477 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002478 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002479 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002480 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002481 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002482 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002483 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002484 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002485
Prabir Pradhan5735a322022-04-11 17:23:34 +00002486 // Verify targeted injection.
2487 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2488 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002489 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002490 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002491 }
2492
Vishnu Nair062a8672021-09-03 16:07:44 -07002493 // Drop touch events if requested by input feature
2494 if (newTouchedWindowHandle != nullptr &&
2495 shouldDropInput(entry, newTouchedWindowHandle)) {
2496 newTouchedWindowHandle = nullptr;
2497 }
2498
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002499 if (newTouchedWindowHandle != nullptr &&
2500 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002501 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2502 oldTouchedWindowHandle->getName().c_str(),
2503 newTouchedWindowHandle->getName().c_str(), displayId);
2504
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002506 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002507 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002508 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002509
2510 const TouchedWindow& touchedWindow =
2511 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2512 addWindowTargetLocked(oldTouchedWindowHandle,
2513 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2514 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515
2516 // Make a slippery entrance into the new window.
2517 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002518 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
2520
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002521 ftl::Flags<InputTarget::Flags> targetFlags =
2522 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002523 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002524 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002527 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 }
2529 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002530 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002531 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002532 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002535 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2536 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002537
2538 // Check if the wallpaper window should deliver the corresponding event.
2539 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002540 tempTouchState, pointerId, targets);
2541 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
2543 }
Arthur Hung96483742022-11-15 03:30:48 +00002544
2545 // Update the pointerIds for non-splittable when it received pointer down.
2546 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2547 // If no split, we suppose all touched windows should receive pointer down.
2548 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2549 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2550 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2551 // Ignore drag window for it should just track one pointer.
2552 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2553 continue;
2554 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002555 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002556 }
2557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002560 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002561 {
2562 std::vector<TouchedWindow> hoveringWindows =
2563 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2564 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002565 std::optional<InputTarget> target =
2566 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2567 touchedWindow.firstDownTimeInTarget);
2568 if (!target) {
2569 continue;
2570 }
2571 // Hardcode to single hovering pointer for now.
2572 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2573 pointerIds.set(entry.pointerProperties[0].id);
2574 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2575 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578
Prabir Pradhan5735a322022-04-11 17:23:34 +00002579 // Ensure that all touched windows are valid for injection.
2580 if (entry.injectionState != nullptr) {
2581 std::string errs;
2582 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002583 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2584 if (err) errs += "\n - " + *err;
2585 }
2586 if (!errs.empty()) {
2587 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2588 "%d:%s",
2589 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002590 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002591 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002592 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002593 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002594
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002595 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2596 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002598 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002599 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002600 if (foregroundWindowHandle) {
2601 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002602 for (InputTarget& target : targets) {
2603 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2604 sp<WindowInfoHandle> targetWindow =
2605 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2606 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2607 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
2610 }
2611 }
2612 }
2613
Harry Cuttsb166c002023-05-09 13:06:05 +00002614 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2615 // only want the system UI to handle these gestures.
2616 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2617 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2618 if (isTouchpadNavGesture) {
2619 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2620 }
2621
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002622 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002623 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002624 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002625 // Windows with hovering pointers are getting persisted inside TouchState.
2626 // Do not send this event to those windows.
2627 continue;
2628 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002629
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002630 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2631 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2632 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002633 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002634
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002635 // During targeted injection, only allow owned targets to receive events
2636 std::erase_if(targets, [&](const InputTarget& target) {
2637 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2638 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2639 if (err) {
2640 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2641 << ": " << (*err);
2642 return true;
2643 }
2644 return false;
2645 });
2646
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002647 if (targets.empty()) {
2648 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2649 outInjectionResult = InputEventInjectionResult::FAILED;
2650 return {};
2651 }
2652
2653 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2654 // window that is actually receiving the entire gesture.
2655 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2656 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2657 })) {
2658 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2659 << entry.getDescription();
2660 outInjectionResult = InputEventInjectionResult::FAILED;
2661 return {};
2662 }
2663
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002664 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002665 // Drop the outside or hover touch windows since we will not care about them
2666 // in the next iteration.
2667 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002670 if (switchedDevice) {
2671 if (DEBUG_FOCUS) {
2672 ALOGD("Conflicting pointer actions: Switched to a different device.");
2673 }
2674 *outConflictingPointerActions = true;
2675 }
2676
2677 if (isHoverAction) {
2678 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002679 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002680 ALOGD_IF(DEBUG_FOCUS,
2681 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002682 *outConflictingPointerActions = true;
2683 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002684 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2685 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2686 tempTouchState.deviceId = entry.deviceId;
2687 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002688 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002689 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2690 // Pointer went up.
2691 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002692 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002693 // All pointers up or canceled.
2694 tempTouchState.reset();
2695 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2696 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002697 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2698 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002699 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002700 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002701 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2702 // One pointer went up.
2703 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2704 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002706 for (size_t i = 0; i < tempTouchState.windows.size();) {
2707 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002708 touchedWindow.pointerIds.reset(pointerId);
2709 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2711 continue;
2712 }
2713 i += 1;
2714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 }
2716
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002717 // Save changes unless the action was scroll in which case the temporary touch
2718 // state was only valid for this one action.
2719 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002720 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002721 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 mTouchStatesByDisplay[displayId] = tempTouchState;
2723 } else {
2724 mTouchStatesByDisplay.erase(displayId);
2725 }
2726 }
2727
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002728 if (tempTouchState.windows.empty()) {
2729 mTouchStatesByDisplay.erase(displayId);
2730 }
2731
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002732 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733}
2734
arthurhung6d4bed92021-03-17 11:59:33 +08002735void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002736 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2737 // have an explicit reason to support it.
2738 constexpr bool isStylus = false;
2739
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002740 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002741 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002742 if (dropWindow) {
2743 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002744 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002745 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002746 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002747 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002748 }
2749 mDragState.reset();
2750}
2751
2752void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002753 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002754 return;
2755 }
2756
arthurhung6d4bed92021-03-17 11:59:33 +08002757 if (!mDragState->isStartDrag) {
2758 mDragState->isStartDrag = true;
2759 mDragState->isStylusButtonDownAtStart =
2760 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2761 }
2762
Arthur Hung54745652022-04-20 07:17:41 +00002763 // Find the pointer index by id.
2764 int32_t pointerIndex = 0;
2765 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2766 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2767 if (pointerProperties.id == mDragState->pointerId) {
2768 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002769 }
Arthur Hung54745652022-04-20 07:17:41 +00002770 }
arthurhung6d4bed92021-03-17 11:59:33 +08002771
Arthur Hung54745652022-04-20 07:17:41 +00002772 if (uint32_t(pointerIndex) == entry.pointerCount) {
2773 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002774 }
2775
2776 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2777 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2778 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2779
2780 switch (maskedAction) {
2781 case AMOTION_EVENT_ACTION_MOVE: {
2782 // Handle the special case : stylus button no longer pressed.
2783 bool isStylusButtonDown =
2784 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2785 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2786 finishDragAndDrop(entry.displayId, x, y);
2787 return;
2788 }
2789
2790 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2791 // until we have an explicit reason to support it.
2792 constexpr bool isStylus = false;
2793
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002794 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002795 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002796 // enqueue drag exit if needed.
2797 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2798 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2799 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002800 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002801 y);
2802 }
2803 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2804 }
2805 // enqueue drag location if needed.
2806 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002807 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002808 }
2809 break;
2810 }
2811
2812 case AMOTION_EVENT_ACTION_POINTER_UP:
2813 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2814 break;
2815 }
2816 // The drag pointer is up.
2817 [[fallthrough]];
2818 case AMOTION_EVENT_ACTION_UP:
2819 finishDragAndDrop(entry.displayId, x, y);
2820 break;
2821 case AMOTION_EVENT_ACTION_CANCEL: {
2822 ALOGD("Receiving cancel when drag and drop.");
2823 sendDropWindowCommandLocked(nullptr, 0, 0);
2824 mDragState.reset();
2825 break;
2826 }
arthurhungb89ccb02020-12-30 16:19:01 +08002827 }
2828}
2829
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002830std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2831 const sp<android::gui::WindowInfoHandle>& windowHandle,
2832 ftl::Flags<InputTarget::Flags> targetFlags,
2833 std::optional<nsecs_t> firstDownTimeInTarget) const {
2834 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2835 if (inputChannel == nullptr) {
2836 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2837 return {};
2838 }
2839 InputTarget inputTarget;
2840 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002841 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002842 inputTarget.flags = targetFlags;
2843 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2844 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2845 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2846 if (displayInfoIt != mDisplayInfos.end()) {
2847 inputTarget.displayTransform = displayInfoIt->second.transform;
2848 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002849 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002850 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2851 }
2852 return inputTarget;
2853}
2854
chaviw98318de2021-05-19 16:45:23 -05002855void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002856 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002857 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002858 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002859 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002860 std::vector<InputTarget>::iterator it =
2861 std::find_if(inputTargets.begin(), inputTargets.end(),
2862 [&windowHandle](const InputTarget& inputTarget) {
2863 return inputTarget.inputChannel->getConnectionToken() ==
2864 windowHandle->getToken();
2865 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002866
chaviw98318de2021-05-19 16:45:23 -05002867 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002868
2869 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002870 std::optional<InputTarget> target =
2871 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2872 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002873 return;
2874 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002875 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002876 it = inputTargets.end() - 1;
2877 }
2878
2879 ALOG_ASSERT(it->flags == targetFlags);
2880 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2881
chaviw1ff3d1e2020-07-01 15:53:47 -07002882 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883}
2884
Michael Wright3dd60e22019-03-27 22:06:44 +00002885void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002886 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002887 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2888 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002889
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002890 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2891 InputTarget target;
2892 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002893 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002894 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2895 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002896 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2897 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002898 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002899 target.setDefaultPointerTransform(target.displayTransform);
2900 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 }
2902}
2903
Robert Carrc9bf1d32020-04-13 17:21:08 -07002904/**
2905 * Indicate whether one window handle should be considered as obscuring
2906 * another window handle. We only check a few preconditions. Actually
2907 * checking the bounds is left to the caller.
2908 */
chaviw98318de2021-05-19 16:45:23 -05002909static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2910 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002911 // Compare by token so cloned layers aren't counted
2912 if (haveSameToken(windowHandle, otherHandle)) {
2913 return false;
2914 }
2915 auto info = windowHandle->getInfo();
2916 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002917 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002918 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002919 } else if (otherInfo->alpha == 0 &&
2920 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002921 // Those act as if they were invisible, so we don't need to flag them.
2922 // We do want to potentially flag touchable windows even if they have 0
2923 // opacity, since they can consume touches and alter the effects of the
2924 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002925 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002926 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2927 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002928 } else if (info->ownerUid == otherInfo->ownerUid) {
2929 // If ownerUid is the same we don't generate occlusion events as there
2930 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002931 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002932 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002933 return false;
2934 } else if (otherInfo->displayId != info->displayId) {
2935 return false;
2936 }
2937 return true;
2938}
2939
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002940/**
2941 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2942 * untrusted, one should check:
2943 *
2944 * 1. If result.hasBlockingOcclusion is true.
2945 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2946 * BLOCK_UNTRUSTED.
2947 *
2948 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2949 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2950 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2951 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2952 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2953 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2954 *
2955 * If neither of those is true, then it means the touch can be allowed.
2956 */
2957InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002958 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2959 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002960 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002961 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002962 TouchOcclusionInfo info;
2963 info.hasBlockingOcclusion = false;
2964 info.obscuringOpacity = 0;
2965 info.obscuringUid = -1;
2966 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002967 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002968 if (windowHandle == otherHandle) {
2969 break; // All future windows are below us. Exit early.
2970 }
chaviw98318de2021-05-19 16:45:23 -05002971 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002972 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2973 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002974 if (DEBUG_TOUCH_OCCLUSION) {
2975 info.debugInfo.push_back(
2976 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2977 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002978 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2979 // we perform the checks below to see if the touch can be propagated or not based on the
2980 // window's touch occlusion mode
2981 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2982 info.hasBlockingOcclusion = true;
2983 info.obscuringUid = otherInfo->ownerUid;
2984 info.obscuringPackage = otherInfo->packageName;
2985 break;
2986 }
2987 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2988 uint32_t uid = otherInfo->ownerUid;
2989 float opacity =
2990 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2991 // Given windows A and B:
2992 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2993 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2994 opacityByUid[uid] = opacity;
2995 if (opacity > info.obscuringOpacity) {
2996 info.obscuringOpacity = opacity;
2997 info.obscuringUid = uid;
2998 info.obscuringPackage = otherInfo->packageName;
2999 }
3000 }
3001 }
3002 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003003 if (DEBUG_TOUCH_OCCLUSION) {
3004 info.debugInfo.push_back(
3005 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3006 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003007 return info;
3008}
3009
chaviw98318de2021-05-19 16:45:23 -05003010std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003011 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003012 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
3013 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3014 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3015 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003016 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
3017 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
3018 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
3019 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
3020 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003021 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003022 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003023}
3024
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003025bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3026 if (occlusionInfo.hasBlockingOcclusion) {
3027 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
3028 occlusionInfo.obscuringUid);
3029 return false;
3030 }
3031 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
3032 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
3033 "%.2f, maximum allowed = %.2f)",
3034 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
3035 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3036 return false;
3037 }
3038 return true;
3039}
3040
chaviw98318de2021-05-19 16:45:23 -05003041bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003044 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3045 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003046 if (windowHandle == otherHandle) {
3047 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
chaviw98318de2021-05-19 16:45:23 -05003049 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003050 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003051 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 return true;
3053 }
3054 }
3055 return false;
3056}
3057
chaviw98318de2021-05-19 16:45:23 -05003058bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003059 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003060 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3061 const WindowInfo* windowInfo = windowHandle->getInfo();
3062 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003063 if (windowHandle == otherHandle) {
3064 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003065 }
chaviw98318de2021-05-19 16:45:23 -05003066 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003067 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003068 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003069 return true;
3070 }
3071 }
3072 return false;
3073}
3074
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003075std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003076 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003077 if (applicationHandle != nullptr) {
3078 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003079 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 } else {
3081 return applicationHandle->getName();
3082 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003083 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003084 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003086 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 }
3088}
3089
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003090void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003091 if (!isUserActivityEvent(eventEntry)) {
3092 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003093 return;
3094 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003095 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003096 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003097 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003098 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003099 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003100 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003101 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102 }
3103 }
3104
3105 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003106 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003107 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003108 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3109 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 return;
3111 }
Josep del Riob3981622023-04-18 15:49:45 +00003112 if (windowDisablingUserActivityInfo != nullptr) {
3113 if (DEBUG_DISPATCH_CYCLE) {
3114 ALOGD("Not poking user activity: disabled by window '%s'.",
3115 windowDisablingUserActivityInfo->name.c_str());
3116 }
3117 return;
3118 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003119 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 eventType = USER_ACTIVITY_EVENT_TOUCH;
3121 }
3122 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003124 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003125 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3126 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 return;
3128 }
Josep del Riob3981622023-04-18 15:49:45 +00003129 // If the key code is unknown, we don't consider it user activity
3130 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3131 return;
3132 }
3133 // Don't inhibit events that were intercepted or are not passed to
3134 // the apps, like system shortcuts
3135 if (windowDisablingUserActivityInfo != nullptr &&
3136 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3137 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3138 if (DEBUG_DISPATCH_CYCLE) {
3139 ALOGD("Not poking user activity: disabled by window '%s'.",
3140 windowDisablingUserActivityInfo->name.c_str());
3141 }
3142 return;
3143 }
3144
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 eventType = USER_ACTIVITY_EVENT_BUTTON;
3146 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003148 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003149 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003150 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 break;
3152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154
Prabir Pradhancef936d2021-07-21 16:17:52 +00003155 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3156 REQUIRES(mLock) {
3157 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003158 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003159 };
3160 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161}
3162
3163void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003164 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003166 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003167 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003169 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003170 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003171 ATRACE_NAME(message.c_str());
3172 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003173 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003174 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003175 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003176 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003177 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003178 inputTarget.getPointerInfoString().c_str());
3179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180
3181 // Skip this event if the connection status is not normal.
3182 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003183 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003184 if (DEBUG_DISPATCH_CYCLE) {
3185 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003186 connection->getInputChannelName().c_str(),
3187 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 return;
3190 }
3191
3192 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003193 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003194 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003196 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003198 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003199 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003200 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3201 logDispatchStateLocked();
3202 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3203 "target on connection "
3204 << connection->getInputChannelName() << " for "
3205 << originalMotionEntry.getDescription();
3206 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003207 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003208 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3209 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 if (!splitMotionEntry) {
3211 return; // split event was dropped
3212 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003213 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3214 std::string reason = std::string("reason=pointer cancel on split window");
3215 android_log_event_list(LOGTAG_INPUT_CANCEL)
3216 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3217 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003218 if (DEBUG_FOCUS) {
3219 ALOGD("channel '%s' ~ Split motion event.",
3220 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003221 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003222 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3224 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 return;
3226 }
3227 }
3228
3229 // Not splitting. Enqueue dispatch entries for the event as is.
3230 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3231}
3232
3233void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003234 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003235 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003236 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003237 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003239 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003240 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003241 ATRACE_NAME(message.c_str());
3242 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003243 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3244 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003245
hongzuo liu95785e22022-09-06 02:51:35 +00003246 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
3248 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003249 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003250 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003251 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003252 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003253 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003254 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003255 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003256 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003257 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003258 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003259 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003260 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261
3262 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003263 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 startDispatchCycleLocked(currentTime, connection);
3265 }
3266}
3267
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003268void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003269 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003270 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003271 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003272 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3274 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003276 ATRACE_NAME(message.c_str());
3277 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3279 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 return;
3281 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282
3283 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3284 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 // This is a new event.
3287 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003288 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003289 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003291 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3292 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003296 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003297 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003298 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003299 dispatchEntry->resolvedAction = keyEntry.action;
3300 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3303 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003304 LOG(WARNING) << "channel " << connection->getInputChannelName()
3305 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 return; // skip the inconsistent event
3307 }
3308 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003311 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003313 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3314 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3315 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3316 static_cast<int32_t>(IdGenerator::Source::OTHER);
3317 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003318 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003320 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003324 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003326 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3328 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003329 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003330 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 }
3332 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003333 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3334 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003335 if (DEBUG_DISPATCH_CYCLE) {
3336 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3337 "enter event",
3338 connection->getInputChannelName().c_str());
3339 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003340 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3341 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003345 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003346 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3347 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3348 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003349 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3351 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003352 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3357 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003358 LOG(WARNING) << "channel " << connection->getInputChannelName()
3359 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 return; // skip the inconsistent event
3361 }
3362
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003363 dispatchEntry->resolvedEventId =
3364 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3365 ? mIdGenerator.nextId()
3366 : motionEntry.id;
3367 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3368 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3369 ") to MotionEvent(id=0x%" PRIx32 ").",
3370 motionEntry.id, dispatchEntry->resolvedEventId);
3371 ATRACE_NAME(message.c_str());
3372 }
3373
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003374 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3375 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3376 // Skip reporting pointer down outside focus to the policy.
3377 break;
3378 }
3379
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003380 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003381 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382
3383 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003385 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003386 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003387 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3388 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003389 break;
3390 }
Chris Yef59a2f42020-10-16 12:55:26 -07003391 case EventEntry::Type::SENSOR: {
3392 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3393 break;
3394 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003395 case EventEntry::Type::CONFIGURATION_CHANGED:
3396 case EventEntry::Type::DEVICE_RESET: {
3397 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003398 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003399 break;
3400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 }
3402
3403 // Remember that we are waiting for this dispatch to complete.
3404 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003405 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
3407
3408 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003409 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003410 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003411}
3412
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003413/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003414 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003415 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003416 * The first role is to log input interaction with windows, which helps determine what the user was
3417 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3418 * that user started interacting with launcher window, as well as any other window that received
3419 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3420 * when the set of tokens that received the event changes. It is not logged again as long as the
3421 * user is interacting with the same windows.
3422 *
3423 * The second role is to track input device activity for metrics collection. For each input event,
3424 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3425 * input_interaction logs, the device interaction is reported even when the set of interaction
3426 * tokens do not change.
3427 *
3428 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3429 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003430 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003431void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3432 const std::vector<InputTarget>& targets) {
3433 int32_t deviceId;
3434 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003435 // Skip ACTION_UP events, and all events other than keys and motions
3436 if (entry.type == EventEntry::Type::KEY) {
3437 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3438 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3439 return;
3440 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003441 deviceId = keyEntry.deviceId;
3442 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003443 } else if (entry.type == EventEntry::Type::MOTION) {
3444 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3445 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003446 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3447 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003448 return;
3449 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003450 deviceId = motionEntry.deviceId;
3451 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003452 } else {
3453 return; // Not a key or a motion
3454 }
3455
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 std::set<int32_t> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003457 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003458 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003460 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003461 continue; // Skip windows that receive ACTION_OUTSIDE
3462 }
3463
3464 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003465 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003466 if (connection == nullptr) {
3467 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003468 }
3469 newConnectionTokens.insert(std::move(token));
3470 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003471 if (target.windowHandle) {
3472 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3473 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003475
3476 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3477 REQUIRES(mLock) {
3478 scoped_unlock unlock(mLock);
3479 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3480 };
3481 postCommandLocked(std::move(command));
3482
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003483 if (newConnectionTokens == mInteractionConnectionTokens) {
3484 return; // no change
3485 }
3486 mInteractionConnectionTokens = newConnectionTokens;
3487
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003488 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003489 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003490 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003491 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003492 std::string message = "Interaction with: " + targetList;
3493 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003494 message += "<none>";
3495 }
3496 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3497}
3498
chaviwfd6d3512019-03-25 13:23:49 -07003499void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003500 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003501 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003502 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3503 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003504 return;
3505 }
3506
Vishnu Nairc519ff72021-01-21 08:23:08 -08003507 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003508 if (focusedToken == token) {
3509 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003510 return;
3511 }
3512
Prabir Pradhancef936d2021-07-21 16:17:52 +00003513 auto command = [this, token]() REQUIRES(mLock) {
3514 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003515 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003516 };
3517 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518}
3519
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003520status_t InputDispatcher::publishMotionEvent(Connection& connection,
3521 DispatchEntry& dispatchEntry) const {
3522 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3523 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3524
3525 PointerCoords scaledCoords[MAX_POINTERS];
3526 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3527
3528 // Set the X and Y offset and X and Y scale depending on the input source.
3529 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003530 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003531 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3532 if (globalScaleFactor != 1.0f) {
3533 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3534 scaledCoords[i] = motionEntry.pointerCoords[i];
3535 // Don't apply window scale here since we don't want scale to affect raw
3536 // coordinates. The scale will be sent back to the client and applied
3537 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003538 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003539 }
3540 usingCoords = scaledCoords;
3541 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003542 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003543 // We don't want the dispatch target to know the coordinates
3544 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3545 scaledCoords[i].clear();
3546 }
3547 usingCoords = scaledCoords;
3548 }
3549
3550 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3551
3552 // Publish the motion event.
3553 return connection.inputPublisher
3554 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3555 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3556 std::move(hmac), dispatchEntry.resolvedAction,
3557 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3558 motionEntry.edgeFlags, motionEntry.metaState,
3559 motionEntry.buttonState, motionEntry.classification,
3560 dispatchEntry.transform, motionEntry.xPrecision,
3561 motionEntry.yPrecision, motionEntry.xCursorPosition,
3562 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3563 motionEntry.downTime, motionEntry.eventTime,
3564 motionEntry.pointerCount, motionEntry.pointerProperties,
3565 usingCoords);
3566}
3567
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003569 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003570 if (ATRACE_ENABLED()) {
3571 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003573 ATRACE_NAME(message.c_str());
3574 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003575 if (DEBUG_DISPATCH_CYCLE) {
3576 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003579 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003580 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003582 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003583 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584
3585 // Publish the event.
3586 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003587 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3588 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003589 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003590 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3591 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3593 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3594 << connection->getInputChannelName();
3595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003597 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 status = connection->inputPublisher
3599 .publishKeyEvent(dispatchEntry->seq,
3600 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3601 keyEntry.source, keyEntry.displayId,
3602 std::move(hmac), dispatchEntry->resolvedAction,
3603 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3604 keyEntry.scanCode, keyEntry.metaState,
3605 keyEntry.repeatCount, keyEntry.downTime,
3606 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003610 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003611 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3612 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3613 << connection->getInputChannelName();
3614 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003615 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003616 break;
3617 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003618
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003619 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003620 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003621 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003622 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003623 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003624 break;
3625 }
3626
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003627 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3628 const TouchModeEntry& touchModeEntry =
3629 static_cast<const TouchModeEntry&>(eventEntry);
3630 status = connection->inputPublisher
3631 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3632 touchModeEntry.inTouchMode);
3633
3634 break;
3635 }
3636
Prabir Pradhan99987712020-11-10 18:43:05 -08003637 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3638 const auto& captureEntry =
3639 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3640 status = connection->inputPublisher
3641 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003642 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003643 break;
3644 }
3645
arthurhungb89ccb02020-12-30 16:19:01 +08003646 case EventEntry::Type::DRAG: {
3647 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3648 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3649 dragEntry.id, dragEntry.x,
3650 dragEntry.y,
3651 dragEntry.isExiting);
3652 break;
3653 }
3654
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003655 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003656 case EventEntry::Type::DEVICE_RESET:
3657 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003658 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003659 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663
3664 // Check the result.
3665 if (status) {
3666 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003667 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003669 "This is unexpected because the wait queue is empty, so the pipe "
3670 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003671 "event to it, status=%s(%d)",
3672 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3673 status);
Harry Cutts33476232023-01-30 19:57:29 +00003674 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 } else {
3676 // Pipe is full and we are waiting for the app to finish process some events
3677 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003678 if (DEBUG_DISPATCH_CYCLE) {
3679 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3680 "waiting for the application to catch up",
3681 connection->getInputChannelName().c_str());
3682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684 } else {
3685 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003686 "status=%s(%d)",
3687 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3688 status);
Harry Cutts33476232023-01-30 19:57:29 +00003689 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691 return;
3692 }
3693
3694 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003695 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3696 connection->outboundQueue.end(),
3697 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003698 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003699 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003700 if (connection->responsive) {
3701 mAnrTracker.insert(dispatchEntry->timeoutTime,
3702 connection->inputChannel->getConnectionToken());
3703 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003704 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
3706}
3707
chaviw09c8d2d2020-08-24 15:48:26 -07003708std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3709 size_t size;
3710 switch (event.type) {
3711 case VerifiedInputEvent::Type::KEY: {
3712 size = sizeof(VerifiedKeyEvent);
3713 break;
3714 }
3715 case VerifiedInputEvent::Type::MOTION: {
3716 size = sizeof(VerifiedMotionEvent);
3717 break;
3718 }
3719 }
3720 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3721 return mHmacKeyManager.sign(start, size);
3722}
3723
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003724const std::array<uint8_t, 32> InputDispatcher::getSignature(
3725 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003726 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003727 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003728 // Only sign events up and down events as the purely move events
3729 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003730 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003731 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003732
3733 VerifiedMotionEvent verifiedEvent =
3734 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3735 verifiedEvent.actionMasked = actionMasked;
3736 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3737 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003738}
3739
3740const std::array<uint8_t, 32> InputDispatcher::getSignature(
3741 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3742 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3743 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3744 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003745 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003746}
3747
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003749 const std::shared_ptr<Connection>& connection,
3750 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003751 if (DEBUG_DISPATCH_CYCLE) {
3752 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3753 connection->getInputChannelName().c_str(), seq, toString(handled));
3754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003756 if (connection->status == Connection::Status::BROKEN ||
3757 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 return;
3759 }
3760
3761 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003762 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3763 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3764 };
3765 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766}
3767
3768void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003769 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003770 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003771 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003772 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3773 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775
3776 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003777 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003778 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003779 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003780 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 // The connection appears to be unrecoverably broken.
3783 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003784 if (connection->status == Connection::Status::NORMAL) {
3785 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
3787 if (notify) {
3788 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003789 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3790 connection->getInputChannelName().c_str());
3791
3792 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003793 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003794 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003795 };
3796 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798 }
3799}
3800
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003801void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3802 while (!queue.empty()) {
3803 DispatchEntry* dispatchEntry = queue.front();
3804 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003805 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807}
3808
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003809void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003811 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813 delete dispatchEntry;
3814}
3815
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003816int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3817 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003818 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003819 if (connection == nullptr) {
3820 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3821 connectionToken.get(), events);
3822 return 0; // remove the callback
3823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 bool notify;
3826 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3827 if (!(events & ALOOPER_EVENT_INPUT)) {
3828 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3829 "events=0x%x",
3830 connection->getInputChannelName().c_str(), events);
3831 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
3833
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003834 nsecs_t currentTime = now();
3835 bool gotOne = false;
3836 status_t status = OK;
3837 for (;;) {
3838 Result<InputPublisher::ConsumerResponse> result =
3839 connection->inputPublisher.receiveConsumerResponse();
3840 if (!result.ok()) {
3841 status = result.error().code();
3842 break;
3843 }
3844
3845 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3846 const InputPublisher::Finished& finish =
3847 std::get<InputPublisher::Finished>(*result);
3848 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3849 finish.consumeTime);
3850 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003851 if (shouldReportMetricsForConnection(*connection)) {
3852 const InputPublisher::Timeline& timeline =
3853 std::get<InputPublisher::Timeline>(*result);
3854 mLatencyTracker
3855 .trackGraphicsLatency(timeline.inputEventId,
3856 connection->inputChannel->getConnectionToken(),
3857 std::move(timeline.graphicsTimeline));
3858 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003859 }
3860 gotOne = true;
3861 }
3862 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003863 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003864 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 return 1;
3866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003869 notify = status != DEAD_OBJECT || !connection->monitor;
3870 if (notify) {
3871 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3872 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3873 status);
3874 }
3875 } else {
3876 // Monitor channels are never explicitly unregistered.
3877 // We do it automatically when the remote endpoint is closed so don't warn about them.
3878 const bool stillHaveWindowHandle =
3879 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3880 notify = !connection->monitor && stillHaveWindowHandle;
3881 if (notify) {
3882 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3883 connection->getInputChannelName().c_str(), events);
3884 }
3885 }
3886
3887 // Remove the channel.
3888 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3889 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890}
3891
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003892void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003894 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003895 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
3897}
3898
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003900 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003901 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003902 for (const Monitor& monitor : monitors) {
3903 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003904 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003905 }
3906}
3907
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003909 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003910 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003911 if (connection == nullptr) {
3912 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003914
3915 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916}
3917
3918void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003919 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003920 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 return;
3922 }
3923
3924 nsecs_t currentTime = now();
3925
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003926 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003927 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003929 if (cancelationEvents.empty()) {
3930 return;
3931 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003932 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3933 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003934 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003935 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003936 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003937 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003938
Arthur Hungb3307ee2021-10-14 10:57:37 +00003939 std::string reason = std::string("reason=").append(options.reason);
3940 android_log_event_list(LOGTAG_INPUT_CANCEL)
3941 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3942
Svet Ganov5d3bc372020-01-26 23:11:07 -08003943 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003944 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003945 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3946 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003947 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003948 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 target.globalScaleFactor = windowInfo->globalScaleFactor;
3950 }
3951 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003952 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003953
hongzuo liu95785e22022-09-06 02:51:35 +00003954 const bool wasEmpty = connection->outboundQueue.empty();
3955
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003956 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003957 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003958 switch (cancelationEventEntry->type) {
3959 case EventEntry::Type::KEY: {
3960 logOutboundKeyDetails("cancel - ",
3961 static_cast<const KeyEntry&>(*cancelationEventEntry));
3962 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003964 case EventEntry::Type::MOTION: {
3965 logOutboundMotionDetails("cancel - ",
3966 static_cast<const MotionEntry&>(*cancelationEventEntry));
3967 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003969 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003970 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003971 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3972 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003973 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003974 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003975 break;
3976 }
3977 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003978 case EventEntry::Type::DEVICE_RESET:
3979 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003981 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003982 break;
3983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
3985
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003986 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003987 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003989
hongzuo liu95785e22022-09-06 02:51:35 +00003990 // If the outbound queue was previously empty, start the dispatch cycle going.
3991 if (wasEmpty && !connection->outboundQueue.empty()) {
3992 startDispatchCycleLocked(currentTime, connection);
3993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994}
3995
Svet Ganov5d3bc372020-01-26 23:11:07 -08003996void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003997 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003998 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003999 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004000 return;
4001 }
4002
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004003 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004004 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004005
4006 if (downEvents.empty()) {
4007 return;
4008 }
4009
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004010 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004011 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4012 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004013 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004014
4015 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004016 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004017 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4018 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004019 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004020 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004021 target.globalScaleFactor = windowInfo->globalScaleFactor;
4022 }
4023 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004024 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004025
hongzuo liu95785e22022-09-06 02:51:35 +00004026 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004027 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004028 switch (downEventEntry->type) {
4029 case EventEntry::Type::MOTION: {
4030 logOutboundMotionDetails("down - ",
4031 static_cast<const MotionEntry&>(*downEventEntry));
4032 break;
4033 }
4034
4035 case EventEntry::Type::KEY:
4036 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004037 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004038 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004039 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004040 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004041 case EventEntry::Type::SENSOR:
4042 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004044 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004045 break;
4046 }
4047 }
4048
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004049 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004050 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004051 }
4052
hongzuo liu95785e22022-09-06 02:51:35 +00004053 // If the outbound queue was previously empty, start the dispatch cycle going.
4054 if (wasEmpty && !connection->outboundQueue.empty()) {
4055 startDispatchCycleLocked(downTime, connection);
4056 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004057}
4058
Arthur Hungc539dbb2022-12-08 07:45:36 +00004059void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4060 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4061 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004062 std::shared_ptr<Connection> wallpaperConnection =
4063 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004064 if (wallpaperConnection != nullptr) {
4065 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4066 }
4067 }
4068}
4069
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004070std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004071 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4072 nsecs_t splitDownTime) {
4073 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
4075 uint32_t splitPointerIndexMap[MAX_POINTERS];
4076 PointerProperties splitPointerProperties[MAX_POINTERS];
4077 PointerCoords splitPointerCoords[MAX_POINTERS];
4078
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004079 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 uint32_t splitPointerCount = 0;
4081
4082 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004085 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004087 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4089 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4090 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004091 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 splitPointerCount += 1;
4093 }
4094 }
4095
4096 if (splitPointerCount != pointerIds.count()) {
4097 // This is bad. We are missing some of the pointers that we expected to deliver.
4098 // Most likely this indicates that we received an ACTION_MOVE events that has
4099 // different pointer ids than we expected based on the previous ACTION_DOWN
4100 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4101 // in this way.
4102 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004103 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004104 "a broken sequence of pointer ids from the input device: %s",
4105 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004106 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 }
4108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004109 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004111 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4112 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4114 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004115 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004117 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 if (pointerIds.count() == 1) {
4119 // The first/last pointer went down/up.
4120 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004122 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4123 ? AMOTION_EVENT_ACTION_CANCEL
4124 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 } else {
4126 // A secondary pointer went down/up.
4127 uint32_t splitPointerIndex = 0;
4128 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4129 splitPointerIndex += 1;
4130 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 action = maskedAction |
4132 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
4134 } else {
4135 // An unrelated pointer changed.
4136 action = AMOTION_EVENT_ACTION_MOVE;
4137 }
4138 }
4139
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004140 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4141 logDispatchStateLocked();
4142 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4143 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4144 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004145 }
4146
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004147 int32_t newId = mIdGenerator.nextId();
4148 if (ATRACE_ENABLED()) {
4149 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4150 ") to MotionEvent(id=0x%" PRIx32 ").",
4151 originalMotionEntry.id, newId);
4152 ATRACE_NAME(message.c_str());
4153 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004154 std::unique_ptr<MotionEntry> splitMotionEntry =
4155 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4156 originalMotionEntry.deviceId, originalMotionEntry.source,
4157 originalMotionEntry.displayId,
4158 originalMotionEntry.policyFlags, action,
4159 originalMotionEntry.actionButton,
4160 originalMotionEntry.flags, originalMotionEntry.metaState,
4161 originalMotionEntry.buttonState,
4162 originalMotionEntry.classification,
4163 originalMotionEntry.edgeFlags,
4164 originalMotionEntry.xPrecision,
4165 originalMotionEntry.yPrecision,
4166 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004167 originalMotionEntry.yCursorPosition, splitDownTime,
4168 splitPointerCount, splitPointerProperties,
4169 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004171 if (originalMotionEntry.injectionState) {
4172 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 splitMotionEntry->injectionState->refCount += 1;
4174 }
4175
4176 return splitMotionEntry;
4177}
4178
Prabir Pradhan678438e2023-04-13 19:32:51 +00004179void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004180 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004181 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Antonio Kantekf16f2832021-09-28 04:39:20 +00004184 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004186 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004188 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004189 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004190 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 } // release lock
4192
4193 if (needWake) {
4194 mLooper->wake();
4195 }
4196}
4197
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004198/**
4199 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004200 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4201 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4202 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4203 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4204 * potentially handle the back key presses.
4205 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4206 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004207 */
4208void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004210 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4211 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004212 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004213 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004214 }
4215 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004216 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004217 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004218 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004219 keyCode = newKeyCode;
4220 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4221 }
4222 } else if (action == AKEY_EVENT_ACTION_UP) {
4223 // In order to maintain a consistent stream of up and down events, check to see if the key
4224 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4225 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004226 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004227 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004228 auto replacementIt = mReplacedKeys.find(replacement);
4229 if (replacementIt != mReplacedKeys.end()) {
4230 keyCode = replacementIt->second;
4231 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004232 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4233 }
4234 }
4235}
4236
Prabir Pradhan678438e2023-04-13 19:32:51 +00004237void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004238 ALOGD_IF(debugInboundEventDetails(),
4239 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4240 ", deviceId=%d, source=%s, displayId=%" PRId32
4241 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4242 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004243 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4244 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4245 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004246 Result<void> keyCheck = validateKeyEvent(args.action);
4247 if (!keyCheck.ok()) {
4248 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 return;
4250 }
4251
Prabir Pradhan678438e2023-04-13 19:32:51 +00004252 uint32_t policyFlags = args.policyFlags;
4253 int32_t flags = args.flags;
4254 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004255 // InputDispatcher tracks and generates key repeats on behalf of
4256 // whatever notifies it, so repeatCount should always be set to 0
4257 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4259 policyFlags |= POLICY_FLAG_VIRTUAL;
4260 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 if (policyFlags & POLICY_FLAG_FUNCTION) {
4263 metaState |= AMETA_FUNCTION_ON;
4264 }
4265
4266 policyFlags |= POLICY_FLAG_TRUSTED;
4267
Prabir Pradhan678438e2023-04-13 19:32:51 +00004268 int32_t keyCode = args.keyCode;
4269 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004270
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004272 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4273 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4274 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
Michael Wright2b3c3302018-03-02 17:19:13 +00004276 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004277 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004278 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4279 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282
Antonio Kantekf16f2832021-09-28 04:39:20 +00004283 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 { // acquire lock
4285 mLock.lock();
4286
4287 if (shouldSendKeyToInputFilterLocked(args)) {
4288 mLock.unlock();
4289
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004290 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004291 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 return; // event was consumed by the filter
4293 }
4294
4295 mLock.lock();
4296 }
4297
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004298 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004299 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4300 args.displayId, policyFlags, args.action, flags, keyCode,
4301 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004303 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 mLock.unlock();
4305 } // release lock
4306
4307 if (needWake) {
4308 mLooper->wake();
4309 }
4310}
4311
Prabir Pradhan678438e2023-04-13 19:32:51 +00004312bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 return mInputFilterEnabled;
4314}
4315
Prabir Pradhan678438e2023-04-13 19:32:51 +00004316void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004317 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004318 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004320 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004321 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4322 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004323 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4324 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4325 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4326 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4327 args.downTime);
4328 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004329 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4330 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004331 i, args.pointerProperties[i].id,
4332 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4333 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4334 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4335 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4336 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4337 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4338 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4339 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4340 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4341 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004344
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004345 Result<void> motionCheck = validateMotionEvent(args.action, args.actionButton,
4346 args.pointerCount, args.pointerProperties);
4347 if (!motionCheck.ok()) {
4348 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004349 return;
4350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004352 if (DEBUG_VERIFY_EVENTS) {
4353 auto [it, _] =
4354 mVerifiersByDisplay.try_emplace(args.displayId,
4355 StringPrintf("display %" PRId32, args.displayId));
4356 Result<void> result =
4357 it->second.processMovement(args.deviceId, args.action, args.pointerCount,
4358 args.pointerProperties, args.pointerCoords, args.flags);
4359 if (!result.ok()) {
4360 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4361 }
4362 }
4363
Prabir Pradhan678438e2023-04-13 19:32:51 +00004364 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004366
4367 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004368 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004369 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4370 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Antonio Kantekf16f2832021-09-28 04:39:20 +00004374 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 { // acquire lock
4376 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004377 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4378 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4379 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004380 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004381 if (touchStateIt != mTouchStatesByDisplay.end()) {
4382 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004383 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004384 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4385 }
4386 }
4387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388
4389 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004390 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004391 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004392 displayTransform = it->second.transform;
4393 }
4394
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 mLock.unlock();
4396
4397 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004398 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4399 args.action, args.actionButton, args.flags, args.edgeFlags,
4400 args.metaState, args.buttonState, args.classification,
4401 displayTransform, args.xPrecision, args.yPrecision,
4402 args.xCursorPosition, args.yCursorPosition, displayTransform,
4403 args.downTime, args.eventTime, args.pointerCount,
4404 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
4406 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004407 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 return; // event was consumed by the filter
4409 }
4410
4411 mLock.lock();
4412 }
4413
4414 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004415 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004416 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4417 args.displayId, policyFlags, args.action,
4418 args.actionButton, args.flags, args.metaState,
4419 args.buttonState, args.classification, args.edgeFlags,
4420 args.xPrecision, args.yPrecision,
4421 args.xCursorPosition, args.yCursorPosition,
4422 args.downTime, args.pointerCount,
4423 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424
Prabir Pradhan678438e2023-04-13 19:32:51 +00004425 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4426 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004427 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004428 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4429 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004430 }
4431
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004432 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 mLock.unlock();
4434 } // release lock
4435
4436 if (needWake) {
4437 mLooper->wake();
4438 }
4439}
4440
Prabir Pradhan678438e2023-04-13 19:32:51 +00004441void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004442 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4444 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004445 args.id, args.eventTime, args.deviceId, args.source,
4446 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004447 }
Chris Yef59a2f42020-10-16 12:55:26 -07004448
Antonio Kantekf16f2832021-09-28 04:39:20 +00004449 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004450 { // acquire lock
4451 mLock.lock();
4452
4453 // Just enqueue a new sensor event.
4454 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004455 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4456 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4457 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004458
4459 needWake = enqueueInboundEventLocked(std::move(newEntry));
4460 mLock.unlock();
4461 } // release lock
4462
4463 if (needWake) {
4464 mLooper->wake();
4465 }
4466}
4467
Prabir Pradhan678438e2023-04-13 19:32:51 +00004468void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004469 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004470 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4471 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004472 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004473 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004474}
4475
Prabir Pradhan678438e2023-04-13 19:32:51 +00004476bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004477 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478}
4479
Prabir Pradhan678438e2023-04-13 19:32:51 +00004480void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004481 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4483 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004484 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486
Prabir Pradhan678438e2023-04-13 19:32:51 +00004487 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004489 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490}
4491
Prabir Pradhan678438e2023-04-13 19:32:51 +00004492void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004493 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004494 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4495 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
Antonio Kantekf16f2832021-09-28 04:39:20 +00004498 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004500 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004502 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004503 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004504 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 } // release lock
4506
4507 if (needWake) {
4508 mLooper->wake();
4509 }
4510}
4511
Prabir Pradhan678438e2023-04-13 19:32:51 +00004512void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004513 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004514 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4515 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004516 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004517
Antonio Kantekf16f2832021-09-28 04:39:20 +00004518 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004519 { // acquire lock
4520 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004521 auto entry =
4522 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004523 needWake = enqueueInboundEventLocked(std::move(entry));
4524 } // release lock
4525
4526 if (needWake) {
4527 mLooper->wake();
4528 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004529}
4530
Prabir Pradhan5735a322022-04-11 17:23:34 +00004531InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4532 std::optional<int32_t> targetUid,
4533 InputEventInjectionSync syncMode,
4534 std::chrono::milliseconds timeout,
4535 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004536 Result<void> eventValidation = validateInputEvent(*event);
4537 if (!eventValidation.ok()) {
4538 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4539 return InputEventInjectionResult::FAILED;
4540 }
4541
Prabir Pradhan65613802023-02-22 23:36:58 +00004542 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004543 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4544 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4545 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4546 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004547 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004548 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
Prabir Pradhan5735a322022-04-11 17:23:34 +00004550 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004552 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004553 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4554 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4555 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4556 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4557 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004558 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004559 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004560 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004561 }
4562
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004563 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004565 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004566 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004567 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004568 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004569 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4570 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4571 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004572 int32_t keyCode = incomingKey.getKeyCode();
4573 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004574 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004576 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004577 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004578 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4579 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4580 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4583 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004584 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585
4586 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4587 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004588 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004589 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4590 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4591 std::to_string(t.duration().count()).c_str());
4592 }
4593 }
4594
4595 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004596 std::unique_ptr<KeyEntry> injectedEntry =
4597 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004598 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004599 incomingKey.getDisplayId(), policyFlags, action,
4600 flags, keyCode, incomingKey.getScanCode(), metaState,
4601 incomingKey.getRepeatCount(),
4602 incomingKey.getDownTime());
4603 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004607 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004608 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004609 const bool isPointerEvent =
4610 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4611 // If a pointer event has no displayId specified, inject it to the default display.
4612 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4613 ? ADISPLAY_ID_DEFAULT
4614 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004615 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004616
4617 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004618 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004619 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004620 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4622 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4623 std::to_string(t.duration().count()).c_str());
4624 }
4625 }
4626
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004627 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4628 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4629 }
4630
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004631 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004632 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4633 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004634 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004635 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4636 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004637 displayId, policyFlags, motionEvent.getAction(),
4638 motionEvent.getActionButton(), flags,
4639 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004640 motionEvent.getButtonState(),
4641 motionEvent.getClassification(),
4642 motionEvent.getEdgeFlags(),
4643 motionEvent.getXPrecision(),
4644 motionEvent.getYPrecision(),
4645 motionEvent.getRawXCursorPosition(),
4646 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004647 motionEvent.getDownTime(),
4648 motionEvent.getPointerCount(),
4649 motionEvent.getPointerProperties(),
4650 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004651 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004652 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004653 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004654 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004655 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004656 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004657 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4658 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004659 displayId, policyFlags,
4660 motionEvent.getAction(),
4661 motionEvent.getActionButton(), flags,
4662 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004663 motionEvent.getButtonState(),
4664 motionEvent.getClassification(),
4665 motionEvent.getEdgeFlags(),
4666 motionEvent.getXPrecision(),
4667 motionEvent.getYPrecision(),
4668 motionEvent.getRawXCursorPosition(),
4669 motionEvent.getRawYCursorPosition(),
4670 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004671 motionEvent.getPointerCount(),
4672 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004673 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004674 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4675 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004676 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004677 }
4678 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004681 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004682 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004683 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 }
4685
Prabir Pradhan5735a322022-04-11 17:23:34 +00004686 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004687 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 injectionState->injectionIsAsync = true;
4689 }
4690
4691 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004692 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693
4694 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004695 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004696 if (DEBUG_INJECTION) {
4697 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4698 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004699 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004700 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 }
4702
4703 mLock.unlock();
4704
4705 if (needWake) {
4706 mLooper->wake();
4707 }
4708
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004711 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004713 if (syncMode == InputEventInjectionSync::NONE) {
4714 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 } else {
4716 for (;;) {
4717 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004718 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 break;
4720 }
4721
4722 nsecs_t remainingTimeout = endTime - now();
4723 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004724 if (DEBUG_INJECTION) {
4725 ALOGD("injectInputEvent - Timed out waiting for injection result "
4726 "to become available.");
4727 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 break;
4730 }
4731
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004732 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 }
4734
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004735 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4736 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004738 if (DEBUG_INJECTION) {
4739 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4740 injectionState->pendingForegroundDispatches);
4741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 nsecs_t remainingTimeout = endTime - now();
4743 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004744 if (DEBUG_INJECTION) {
4745 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4746 "dispatches to finish.");
4747 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004748 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 break;
4750 }
4751
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004752 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 }
4754 }
4755 }
4756
4757 injectionState->release();
4758 } // release lock
4759
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004760 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004761 LOG(DEBUG) << "injectInputEvent - Finished with result "
4762 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764
4765 return injectionResult;
4766}
4767
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004768std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004769 std::array<uint8_t, 32> calculatedHmac;
4770 std::unique_ptr<VerifiedInputEvent> result;
4771 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004772 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004773 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4774 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4775 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004776 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004777 break;
4778 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004779 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004780 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4781 VerifiedMotionEvent verifiedMotionEvent =
4782 verifiedMotionEventFromMotionEvent(motionEvent);
4783 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004784 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004785 break;
4786 }
4787 default: {
4788 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4789 return nullptr;
4790 }
4791 }
4792 if (calculatedHmac == INVALID_HMAC) {
4793 return nullptr;
4794 }
tyiu1573a672023-02-21 22:38:32 +00004795 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004796 return nullptr;
4797 }
4798 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004799}
4800
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004801void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004802 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004803 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004805 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004806 LOG(DEBUG) << "Setting input event injection result to "
4807 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004810 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 // Log the outcome since the injector did not wait for the injection result.
4812 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 ALOGV("Asynchronous input event injection succeeded.");
4815 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004816 case InputEventInjectionResult::TARGET_MISMATCH:
4817 ALOGV("Asynchronous input event injection target mismatch.");
4818 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004819 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004820 ALOGW("Asynchronous input event injection failed.");
4821 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004822 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823 ALOGW("Asynchronous input event injection timed out.");
4824 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004825 case InputEventInjectionResult::PENDING:
4826 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4827 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 }
4829 }
4830
4831 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004832 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
4834}
4835
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004836void InputDispatcher::transformMotionEntryForInjectionLocked(
4837 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004838 // Input injection works in the logical display coordinate space, but the input pipeline works
4839 // display space, so we need to transform the injected events accordingly.
4840 const auto it = mDisplayInfos.find(entry.displayId);
4841 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004842 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004843
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004844 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4845 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4846 const vec2 cursor =
4847 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4848 {entry.xCursorPosition, entry.yCursorPosition});
4849 entry.xCursorPosition = cursor.x;
4850 entry.yCursorPosition = cursor.y;
4851 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004852 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004853 entry.pointerCoords[i] =
4854 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4855 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004856 }
4857}
4858
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004859void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4860 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 if (injectionState) {
4862 injectionState->pendingForegroundDispatches += 1;
4863 }
4864}
4865
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004866void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4867 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 if (injectionState) {
4869 injectionState->pendingForegroundDispatches -= 1;
4870
4871 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004872 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874 }
4875}
4876
chaviw98318de2021-05-19 16:45:23 -05004877const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004878 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004879 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004880 auto it = mWindowHandlesByDisplay.find(displayId);
4881 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004882}
4883
chaviw98318de2021-05-19 16:45:23 -05004884sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004885 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004886 if (windowHandleToken == nullptr) {
4887 return nullptr;
4888 }
4889
Arthur Hungb92218b2018-08-14 12:00:21 +08004890 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004891 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4892 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004893 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004894 return windowHandle;
4895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 }
4897 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004898 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899}
4900
chaviw98318de2021-05-19 16:45:23 -05004901sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4902 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004903 if (windowHandleToken == nullptr) {
4904 return nullptr;
4905 }
4906
chaviw98318de2021-05-19 16:45:23 -05004907 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004908 if (windowHandle->getToken() == windowHandleToken) {
4909 return windowHandle;
4910 }
4911 }
4912 return nullptr;
4913}
4914
chaviw98318de2021-05-19 16:45:23 -05004915sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4916 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004917 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004918 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4919 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004920 if (handle->getId() == windowHandle->getId() &&
4921 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004922 if (windowHandle->getInfo()->displayId != it.first) {
4923 ALOGE("Found window %s in display %" PRId32
4924 ", but it should belong to display %" PRId32,
4925 windowHandle->getName().c_str(), it.first,
4926 windowHandle->getInfo()->displayId);
4927 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004928 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 }
4931 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004932 return nullptr;
4933}
4934
chaviw98318de2021-05-19 16:45:23 -05004935sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004936 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4937 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938}
4939
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004940ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4941 auto displayInfoIt = mDisplayInfos.find(displayId);
4942 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4943 : kIdentityTransform;
4944}
4945
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004946bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4947 const MotionEntry& motionEntry) const {
4948 const WindowInfo& info = *window->getInfo();
4949
4950 // Skip spy window targets that are not valid for targeted injection.
4951 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004952 return false;
4953 }
4954
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004955 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4956 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4957 return false;
4958 }
4959
4960 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4961 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4962 window->getName().c_str());
4963 return false;
4964 }
4965
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004966 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004967 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004968 ALOGW("Not sending touch to %s because there's no corresponding connection",
4969 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004970 return false;
4971 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004972
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004973 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004974 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004975 return false;
4976 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004977
4978 // Drop events that can't be trusted due to occlusion
4979 const auto [x, y] = resolveTouchedPosition(motionEntry);
4980 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4981 if (!isTouchTrustedLocked(occlusionInfo)) {
4982 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004983 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004984 for (const auto& log : occlusionInfo.debugInfo) {
4985 ALOGD("%s", log.c_str());
4986 }
4987 }
4988 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4989 occlusionInfo.obscuringUid);
4990 return false;
4991 }
4992
4993 // Drop touch events if requested by input feature
4994 if (shouldDropInput(motionEntry, window)) {
4995 return false;
4996 }
4997
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004998 return true;
4999}
5000
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005001std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5002 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005003 auto connectionIt = mConnectionsByToken.find(token);
5004 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005005 return nullptr;
5006 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005007 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005008}
5009
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005010void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005011 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5012 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005013 // Remove all handles on a display if there are no windows left.
5014 mWindowHandlesByDisplay.erase(displayId);
5015 return;
5016 }
5017
5018 // Since we compare the pointer of input window handles across window updates, we need
5019 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005020 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5021 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5022 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005023 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005024 }
5025
chaviw98318de2021-05-19 16:45:23 -05005026 std::vector<sp<WindowInfoHandle>> newHandles;
5027 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005028 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005029 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005030 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005031 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005032 const bool canReceiveInput =
5033 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5034 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005035 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005036 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005037 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005038 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005039 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005040 }
5041
5042 if (info->displayId != displayId) {
5043 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5044 handle->getName().c_str(), displayId, info->displayId);
5045 continue;
5046 }
5047
Robert Carredd13602020-04-13 17:24:34 -07005048 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5049 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005050 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005051 oldHandle->updateFrom(handle);
5052 newHandles.push_back(oldHandle);
5053 } else {
5054 newHandles.push_back(handle);
5055 }
5056 }
5057
5058 // Insert or replace
5059 mWindowHandlesByDisplay[displayId] = newHandles;
5060}
5061
Arthur Hung72d8dc32020-03-28 00:48:39 +00005062void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005063 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005064 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005065 { // acquire lock
5066 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005067 for (const auto& [displayId, handles] : handlesPerDisplay) {
5068 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005069 }
5070 }
5071 // Wake up poll loop since it may need to make new input dispatching choices.
5072 mLooper->wake();
5073}
5074
Arthur Hungb92218b2018-08-14 12:00:21 +08005075/**
5076 * Called from InputManagerService, update window handle list by displayId that can receive input.
5077 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5078 * If set an empty list, remove all handles from the specific display.
5079 * For focused handle, check if need to change and send a cancel event to previous one.
5080 * For removed handle, check if need to send a cancel event if already in touch.
5081 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005082void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005083 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005084 if (DEBUG_FOCUS) {
5085 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005086 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005087 windowList += iwh->getName() + " ";
5088 }
5089 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091
Prabir Pradhand65552b2021-10-07 11:23:50 -07005092 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005093 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005094 const WindowInfo& info = *window->getInfo();
5095
5096 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005097 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005098 if (noInputWindow && window->getToken() != nullptr) {
5099 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5100 window->getName().c_str());
5101 window->releaseChannel();
5102 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005103
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005104 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005105 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5106 !info.inputConfig.test(
5107 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005108 "%s has feature SPY, but is not a trusted overlay.",
5109 window->getName().c_str());
5110
Prabir Pradhand65552b2021-10-07 11:23:50 -07005111 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005112 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5113 !info.inputConfig.test(
5114 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005115 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5116 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005117 }
5118
Arthur Hung72d8dc32020-03-28 00:48:39 +00005119 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005120 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005122 // Save the old windows' orientation by ID before it gets updated.
5123 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005124 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005125 oldWindowOrientations.emplace(handle->getId(),
5126 handle->getInfo()->transform.getOrientation());
5127 }
5128
chaviw98318de2021-05-19 16:45:23 -05005129 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005130
chaviw98318de2021-05-19 16:45:23 -05005131 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005132
Vishnu Nairc519ff72021-01-21 08:23:08 -08005133 std::optional<FocusResolver::FocusChanges> changes =
5134 mFocusResolver.setInputWindows(displayId, windowHandles);
5135 if (changes) {
5136 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005139 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5140 mTouchStatesByDisplay.find(displayId);
5141 if (stateIt != mTouchStatesByDisplay.end()) {
5142 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 for (size_t i = 0; i < state.windows.size();) {
5144 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005145 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005146 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147 ALOGD("Touched window was removed: %s in display %" PRId32,
5148 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005150 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5152 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005153 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005154 "touched window was removed");
5155 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005156 // Since we are about to drop the touch, cancel the events for the wallpaper as
5157 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005158 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005159 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5160 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005161 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005162 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005165 state.windows.erase(state.windows.begin() + i);
5166 } else {
5167 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 }
5169 }
arthurhungb89ccb02020-12-30 16:19:01 +08005170
arthurhung6d4bed92021-03-17 11:59:33 +08005171 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005172 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005173 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005174 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005175 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005176 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5177 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005178 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005179 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005180 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005181
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005182 // Determine if the orientation of any of the input windows have changed, and cancel all
5183 // pointer events if necessary.
5184 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5185 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5186 if (newWindowHandle != nullptr &&
5187 newWindowHandle->getInfo()->transform.getOrientation() !=
5188 oldWindowOrientations[oldWindowHandle->getId()]) {
5189 std::shared_ptr<InputChannel> inputChannel =
5190 getInputChannelLocked(newWindowHandle->getToken());
5191 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005192 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005193 "touched window's orientation changed");
5194 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005195 }
5196 }
5197 }
5198
Arthur Hung72d8dc32020-03-28 00:48:39 +00005199 // Release information for windows that are no longer present.
5200 // This ensures that unused input channels are released promptly.
5201 // Otherwise, they might stick around until the window handle is destroyed
5202 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005203 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005204 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005205 if (DEBUG_FOCUS) {
5206 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005207 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005208 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005209 }
chaviw291d88a2019-02-14 10:33:58 -08005210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211}
5212
5213void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005214 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005215 if (DEBUG_FOCUS) {
5216 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5217 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5218 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005219 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005220 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005221 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 } // release lock
5223
5224 // Wake up poll loop since it may need to make new input dispatching choices.
5225 mLooper->wake();
5226}
5227
Vishnu Nair599f1412021-06-21 10:39:58 -07005228void InputDispatcher::setFocusedApplicationLocked(
5229 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5230 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5231 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5232
5233 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5234 return; // This application is already focused. No need to wake up or change anything.
5235 }
5236
5237 // Set the new application handle.
5238 if (inputApplicationHandle != nullptr) {
5239 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5240 } else {
5241 mFocusedApplicationHandlesByDisplay.erase(displayId);
5242 }
5243
5244 // No matter what the old focused application was, stop waiting on it because it is
5245 // no longer focused.
5246 resetNoFocusedWindowTimeoutLocked();
5247}
5248
Tiger Huang721e26f2018-07-24 22:26:19 +08005249/**
5250 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5251 * the display not specified.
5252 *
5253 * We track any unreleased events for each window. If a window loses the ability to receive the
5254 * released event, we will send a cancel event to it. So when the focused display is changed, we
5255 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5256 * display. The display-specified events won't be affected.
5257 */
5258void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005259 if (DEBUG_FOCUS) {
5260 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5261 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005262 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005263 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005264
5265 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005266 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005267 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005268 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005269 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005270 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005271 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005272 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005273 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005274 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005275 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005276 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5277 }
5278 }
5279 mFocusedDisplayId = displayId;
5280
Chris Ye3c2d6f52020-08-09 10:39:48 -07005281 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005282 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005283 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005284
Vishnu Nairad321cd2020-08-20 16:40:21 -07005285 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005286 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005287 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005288 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005289 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005290 }
5291 }
5292 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005293 } // release lock
5294
5295 // Wake up poll loop since it may need to make new input dispatching choices.
5296 mLooper->wake();
5297}
5298
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005300 if (DEBUG_FOCUS) {
5301 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303
5304 bool changed;
5305 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005306 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307
5308 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5309 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005310 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
5312
5313 if (mDispatchEnabled && !enabled) {
5314 resetAndDropEverythingLocked("dispatcher is being disabled");
5315 }
5316
5317 mDispatchEnabled = enabled;
5318 mDispatchFrozen = frozen;
5319 changed = true;
5320 } else {
5321 changed = false;
5322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 } // release lock
5324
5325 if (changed) {
5326 // Wake up poll loop since it may need to make new input dispatching choices.
5327 mLooper->wake();
5328 }
5329}
5330
5331void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005332 if (DEBUG_FOCUS) {
5333 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335
5336 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005337 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338
5339 if (mInputFilterEnabled == enabled) {
5340 return;
5341 }
5342
5343 mInputFilterEnabled = enabled;
5344 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5345 } // release lock
5346
5347 // Wake up poll loop since there might be work to do to drop everything.
5348 mLooper->wake();
5349}
5350
Antonio Kanteka042c022022-07-06 16:51:07 -07005351bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5352 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005353 bool needWake = false;
5354 {
5355 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005356 ALOGD_IF(DEBUG_TOUCH_MODE,
5357 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5358 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5359 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5360 mTouchModePerDisplay.count(displayId) == 0
5361 ? "not set"
5362 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5363
Antonio Kantek15beb512022-06-13 22:35:41 +00005364 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5365 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005366 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005367 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005368 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005369 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5370 !recentWindowsAreOwnedByLocked(pid, uid)) {
5371 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5372 "window nor none of the previously interacted window",
5373 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005374 return false;
5375 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005376 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005377 mTouchModePerDisplay[displayId] = inTouchMode;
5378 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5379 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005380 needWake = enqueueInboundEventLocked(std::move(entry));
5381 } // release lock
5382
5383 if (needWake) {
5384 mLooper->wake();
5385 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005386 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005387}
5388
Antonio Kantek48710e42022-03-24 14:19:30 -07005389bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5390 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5391 if (focusedToken == nullptr) {
5392 return false;
5393 }
5394 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5395 return isWindowOwnedBy(windowHandle, pid, uid);
5396}
5397
5398bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5399 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5400 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5401 const sp<WindowInfoHandle> windowHandle =
5402 getWindowHandleLocked(connectionToken);
5403 return isWindowOwnedBy(windowHandle, pid, uid);
5404 }) != mInteractionConnectionTokens.end();
5405}
5406
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005407void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5408 if (opacity < 0 || opacity > 1) {
5409 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5410 return;
5411 }
5412
5413 std::scoped_lock lock(mLock);
5414 mMaximumObscuringOpacityForTouch = opacity;
5415}
5416
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005417std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5418InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005419 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5420 for (TouchedWindow& w : state.windows) {
5421 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005422 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005423 }
5424 }
5425 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005426 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005427}
5428
arthurhungb89ccb02020-12-30 16:19:01 +08005429bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5430 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005431 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005432 if (DEBUG_FOCUS) {
5433 ALOGD("Trivial transfer to same window.");
5434 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005435 return true;
5436 }
5437
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005439 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440
Arthur Hungabbb9d82021-09-01 14:52:30 +00005441 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005442 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005443 if (state == nullptr || touchedWindow == nullptr) {
5444 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 return false;
5446 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005447
Arthur Hungabbb9d82021-09-01 14:52:30 +00005448 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5449 if (toWindowHandle == nullptr) {
5450 ALOGW("Cannot transfer focus because to window not found.");
5451 return false;
5452 }
5453
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005454 if (DEBUG_FOCUS) {
5455 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005456 touchedWindow->windowHandle->getName().c_str(),
5457 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 }
5459
Arthur Hungabbb9d82021-09-01 14:52:30 +00005460 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005461 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005462 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005463 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005464 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465
Arthur Hungabbb9d82021-09-01 14:52:30 +00005466 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005467 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005468 ftl::Flags<InputTarget::Flags> newTargetFlags =
5469 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005470 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005471 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005472 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005473 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474
Arthur Hungabbb9d82021-09-01 14:52:30 +00005475 // Store the dragging window.
5476 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005477 if (pointerIds.count() != 1) {
5478 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5479 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005480 return false;
5481 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005482 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005483 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005484 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 }
5486
Arthur Hungabbb9d82021-09-01 14:52:30 +00005487 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005488 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5489 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005490 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005491 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005492 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005493 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005494 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005496 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5497 newTargetFlags);
5498
5499 // Check if the wallpaper window should deliver the corresponding event.
5500 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5501 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503 } // release lock
5504
5505 // Wake up poll loop since it may need to make new input dispatching choices.
5506 mLooper->wake();
5507 return true;
5508}
5509
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005510/**
5511 * Get the touched foreground window on the given display.
5512 * Return null if there are no windows touched on that display, or if more than one foreground
5513 * window is being touched.
5514 */
5515sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5516 auto stateIt = mTouchStatesByDisplay.find(displayId);
5517 if (stateIt == mTouchStatesByDisplay.end()) {
5518 ALOGI("No touch state on display %" PRId32, displayId);
5519 return nullptr;
5520 }
5521
5522 const TouchState& state = stateIt->second;
5523 sp<WindowInfoHandle> touchedForegroundWindow;
5524 // If multiple foreground windows are touched, return nullptr
5525 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005526 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005527 if (touchedForegroundWindow != nullptr) {
5528 ALOGI("Two or more foreground windows: %s and %s",
5529 touchedForegroundWindow->getName().c_str(),
5530 window.windowHandle->getName().c_str());
5531 return nullptr;
5532 }
5533 touchedForegroundWindow = window.windowHandle;
5534 }
5535 }
5536 return touchedForegroundWindow;
5537}
5538
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005539// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005540bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005541 sp<IBinder> fromToken;
5542 { // acquire lock
5543 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005544 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005545 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005546 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5547 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005548 return false;
5549 }
5550
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005551 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5552 if (from == nullptr) {
5553 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5554 return false;
5555 }
5556
5557 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005558 } // release lock
5559
5560 return transferTouchFocus(fromToken, destChannelToken);
5561}
5562
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005564 if (DEBUG_FOCUS) {
5565 ALOGD("Resetting and dropping all events (%s).", reason);
5566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567
Michael Wrightfb04fd52022-11-24 22:31:11 +00005568 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 synthesizeCancelationEventsForAllConnectionsLocked(options);
5570
5571 resetKeyRepeatLocked();
5572 releasePendingEventLocked();
5573 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005574 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005576 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005577 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005578 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579}
5580
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005581void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005582 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 dumpDispatchStateLocked(dump);
5584
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005585 std::istringstream stream(dump);
5586 std::string line;
5587
5588 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005589 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 }
5591}
5592
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005593std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005594 std::string dump;
5595
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005596 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5597 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005598
5599 std::string windowName = "None";
5600 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005601 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005602 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5603 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5604 : "token has capture without window";
5605 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005606 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005607
5608 return dump;
5609}
5610
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005611void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005612 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5613 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5614 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005615 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616
Tiger Huang721e26f2018-07-24 22:26:19 +08005617 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5618 dump += StringPrintf(INDENT "FocusedApplications:\n");
5619 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5620 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005621 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005622 const std::chrono::duration timeout =
5623 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005624 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005625 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005626 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005629 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005631
Vishnu Nairc519ff72021-01-21 08:23:08 -08005632 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005633 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005635 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005636 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005637 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005638 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5639 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005642 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 }
5644
arthurhung6d4bed92021-03-17 11:59:33 +08005645 if (mDragState) {
5646 dump += StringPrintf(INDENT "DragState:\n");
5647 mDragState->dump(dump, INDENT2);
5648 }
5649
Arthur Hungb92218b2018-08-14 12:00:21 +08005650 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005651 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5652 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5653 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5654 const auto& displayInfo = it->second;
5655 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5656 displayInfo.logicalHeight);
5657 displayInfo.transform.dump(dump, "transform", INDENT4);
5658 } else {
5659 dump += INDENT2 "No DisplayInfo found!\n";
5660 }
5661
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005662 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005663 dump += INDENT2 "Windows:\n";
5664 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005665 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5666 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005668 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005669 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005670 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005671 "applicationInfo.name=%s, "
5672 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005673 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005674 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005675 windowInfo->displayId,
5676 windowInfo->inputConfig.string().c_str(),
5677 windowInfo->alpha, windowInfo->frameLeft,
5678 windowInfo->frameTop, windowInfo->frameRight,
5679 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005680 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005681 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005682 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005683 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005684 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005685 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005686 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005687 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005688 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005689 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005690 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005691 }
5692 } else {
5693 dump += INDENT2 "Windows: <none>\n";
5694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005697 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 }
5699
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005700 if (!mGlobalMonitorsByDisplay.empty()) {
5701 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5702 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005703 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005706 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005709 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710
5711 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005712 if (!mRecentQueue.empty()) {
5713 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005714 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005715 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005716 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005717 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005720 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 }
5722
5723 // Dump event currently being dispatched.
5724 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005725 dump += INDENT "PendingEvent:\n";
5726 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005727 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005728 dump += StringPrintf(", age=%" PRId64 "ms\n",
5729 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005731 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733
5734 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005735 if (!mInboundQueue.empty()) {
5736 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005737 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005738 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005739 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005740 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005743 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
5745
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005746 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005747 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005748 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005749 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005750 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005751 }
5752 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005753 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005754 }
5755
Prabir Pradhancef936d2021-07-21 16:17:52 +00005756 if (!mCommandQueue.empty()) {
5757 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5758 } else {
5759 dump += INDENT "CommandQueue: <empty>\n";
5760 }
5761
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005762 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005763 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005764 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005765 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005766 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005767 connection->inputChannel->getFd().get(),
5768 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005769 connection->getWindowName().c_str(),
5770 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005771 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005773 if (!connection->outboundQueue.empty()) {
5774 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5775 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005776 dump += dumpQueue(connection->outboundQueue, currentTime);
5777
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005779 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005782 if (!connection->waitQueue.empty()) {
5783 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5784 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005785 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005787 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
5789 }
5790 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005791 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793
5794 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005795 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5796 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005798 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799 }
5800
Antonio Kantek15beb512022-06-13 22:35:41 +00005801 if (!mTouchModePerDisplay.empty()) {
5802 dump += INDENT "TouchModePerDisplay:\n";
5803 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5804 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5805 std::to_string(touchMode).c_str());
5806 }
5807 } else {
5808 dump += INDENT "TouchModePerDisplay: <none>\n";
5809 }
5810
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005811 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005812 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5813 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5814 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005815 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005816 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817}
5818
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005819void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005820 const size_t numMonitors = monitors.size();
5821 for (size_t i = 0; i < numMonitors; i++) {
5822 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005823 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005824 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5825 dump += "\n";
5826 }
5827}
5828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005829class LooperEventCallback : public LooperCallback {
5830public:
5831 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5832 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5833
5834private:
5835 std::function<int(int events)> mCallback;
5836};
5837
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005838Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005839 if (DEBUG_CHANNEL_CREATION) {
5840 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005843 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005844 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005845 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005846
5847 if (result) {
5848 return base::Error(result) << "Failed to open input channel pair with name " << name;
5849 }
5850
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005852 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005853 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005854 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005855 std::shared_ptr<Connection> connection =
5856 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5857 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005859 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5860 ALOGE("Created a new connection, but the token %p is already known", token.get());
5861 }
5862 mConnectionsByToken.emplace(token, connection);
5863
5864 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5865 this, std::placeholders::_1, token);
5866
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005867 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5868 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 } // release lock
5870
5871 // Wake the looper because some connections have changed.
5872 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005873 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874}
5875
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005876Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005877 const std::string& name,
5878 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005879 std::shared_ptr<InputChannel> serverChannel;
5880 std::unique_ptr<InputChannel> clientChannel;
5881 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5882 if (result) {
5883 return base::Error(result) << "Failed to open input channel pair with name " << name;
5884 }
5885
Michael Wright3dd60e22019-03-27 22:06:44 +00005886 { // acquire lock
5887 std::scoped_lock _l(mLock);
5888
5889 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005890 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5891 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005892 }
5893
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005894 std::shared_ptr<Connection> connection =
5895 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005896 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005897 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005898
5899 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5900 ALOGE("Created a new connection, but the token %p is already known", token.get());
5901 }
5902 mConnectionsByToken.emplace(token, connection);
5903 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5904 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005905
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005906 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005907
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005908 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5909 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005910 }
Garfield Tan15601662020-09-22 15:32:38 -07005911
Michael Wright3dd60e22019-03-27 22:06:44 +00005912 // Wake the looper because some connections have changed.
5913 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005914 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005915}
5916
Garfield Tan15601662020-09-22 15:32:38 -07005917status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005919 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920
Harry Cutts33476232023-01-30 19:57:29 +00005921 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922 if (status) {
5923 return status;
5924 }
5925 } // release lock
5926
5927 // Wake the poll loop because removing the connection may have changed the current
5928 // synchronization state.
5929 mLooper->wake();
5930 return OK;
5931}
5932
Garfield Tan15601662020-09-22 15:32:38 -07005933status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5934 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005935 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005936 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005937 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 return BAD_VALUE;
5939 }
5940
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005941 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005942
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005944 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 }
5946
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005947 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948
5949 nsecs_t currentTime = now();
5950 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5951
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005952 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953 return OK;
5954}
5955
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005956void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005957 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5958 auto& [displayId, monitors] = *it;
5959 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5960 return monitor.inputChannel->getConnectionToken() == connectionToken;
5961 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005962
Michael Wright3dd60e22019-03-27 22:06:44 +00005963 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005964 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005965 } else {
5966 ++it;
5967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 }
5969}
5970
Michael Wright3dd60e22019-03-27 22:06:44 +00005971status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005972 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005973 return pilferPointersLocked(token);
5974}
Michael Wright3dd60e22019-03-27 22:06:44 +00005975
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005976status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005977 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5978 if (!requestingChannel) {
5979 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5980 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005981 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005982
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005983 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005984 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5986 " Ignoring.");
5987 return BAD_VALUE;
5988 }
5989
5990 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005991 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005992 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005993 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005994 "input channel stole pointer stream");
5995 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005996 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005997 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005998 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005999 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006000 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006001 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006002 if (channel != nullptr && channel->getConnectionToken() != token) {
6003 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6004 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6005 canceledWindows += channel->getName();
6006 }
6007 }
6008 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6009 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6010 canceledWindows.c_str());
6011
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006012 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006013 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006014 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006015
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006016 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006017 return OK;
6018}
6019
Prabir Pradhan99987712020-11-10 18:43:05 -08006020void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6021 { // acquire lock
6022 std::scoped_lock _l(mLock);
6023 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006024 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006025 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6026 windowHandle != nullptr ? windowHandle->getName().c_str()
6027 : "token without window");
6028 }
6029
Vishnu Nairc519ff72021-01-21 08:23:08 -08006030 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006031 if (focusedToken != windowToken) {
6032 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6033 enabled ? "enable" : "disable");
6034 return;
6035 }
6036
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006037 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006038 ALOGW("Ignoring request to %s Pointer Capture: "
6039 "window has %s requested pointer capture.",
6040 enabled ? "enable" : "disable", enabled ? "already" : "not");
6041 return;
6042 }
6043
Christine Franksb768bb42021-11-29 12:11:31 -08006044 if (enabled) {
6045 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6046 mIneligibleDisplaysForPointerCapture.end(),
6047 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6048 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6049 return;
6050 }
6051 }
6052
Prabir Pradhan99987712020-11-10 18:43:05 -08006053 setPointerCaptureLocked(enabled);
6054 } // release lock
6055
6056 // Wake the thread to process command entries.
6057 mLooper->wake();
6058}
6059
Christine Franksb768bb42021-11-29 12:11:31 -08006060void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6061 { // acquire lock
6062 std::scoped_lock _l(mLock);
6063 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6064 if (!isEligible) {
6065 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6066 }
6067 } // release lock
6068}
6069
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
6071 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006072 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006073 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006075 }
6076 }
6077 }
6078 return std::nullopt;
6079}
6080
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006081std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6082 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006083 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006084 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006085 }
6086
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006087 for (const auto& [token, connection] : mConnectionsByToken) {
6088 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006089 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 }
6091 }
Robert Carr4e670e52018-08-15 13:26:12 -07006092
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006093 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094}
6095
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006096std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006097 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006098 if (connection == nullptr) {
6099 return "<nullptr>";
6100 }
6101 return connection->getInputChannelName();
6102}
6103
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006104void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006105 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006106 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006107}
6108
Prabir Pradhancef936d2021-07-21 16:17:52 +00006109void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006110 const std::shared_ptr<Connection>& connection,
6111 uint32_t seq, bool handled,
6112 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006113 // Handle post-event policy actions.
6114 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6115 if (dispatchEntryIt == connection->waitQueue.end()) {
6116 return;
6117 }
6118 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6119 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6120 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6121 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6122 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6123 }
6124 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6125 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6126 connection->inputChannel->getConnectionToken(),
6127 dispatchEntry->deliveryTime, consumeTime, finishTime);
6128 }
6129
6130 bool restartEvent;
6131 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6132 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6133 restartEvent =
6134 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6135 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6136 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6137 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6138 handled);
6139 } else {
6140 restartEvent = false;
6141 }
6142
6143 // Dequeue the event and start the next cycle.
6144 // Because the lock might have been released, it is possible that the
6145 // contents of the wait queue to have been drained, so we need to double-check
6146 // a few things.
6147 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6148 if (dispatchEntryIt != connection->waitQueue.end()) {
6149 dispatchEntry = *dispatchEntryIt;
6150 connection->waitQueue.erase(dispatchEntryIt);
6151 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6152 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6153 if (!connection->responsive) {
6154 connection->responsive = isConnectionResponsive(*connection);
6155 if (connection->responsive) {
6156 // The connection was unresponsive, and now it's responsive.
6157 processConnectionResponsiveLocked(*connection);
6158 }
6159 }
6160 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006161 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006162 connection->outboundQueue.push_front(dispatchEntry);
6163 traceOutboundQueueLength(*connection);
6164 } else {
6165 releaseDispatchEntry(dispatchEntry);
6166 }
6167 }
6168
6169 // Start the next dispatch cycle for this connection.
6170 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171}
6172
Prabir Pradhancef936d2021-07-21 16:17:52 +00006173void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6174 const sp<IBinder>& newToken) {
6175 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6176 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006177 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006178 };
6179 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180}
6181
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6183 auto command = [this, token, x, y]() REQUIRES(mLock) {
6184 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006185 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006186 };
6187 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006188}
6189
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006190void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006191 if (connection == nullptr) {
6192 LOG_ALWAYS_FATAL("Caller must check for nullness");
6193 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006194 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6195 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006196 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006197 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006198 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006199 return;
6200 }
6201 /**
6202 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6203 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6204 * has changed. This could cause newer entries to time out before the already dispatched
6205 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6206 * processes the events linearly. So providing information about the oldest entry seems to be
6207 * most useful.
6208 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006209 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006210 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6211 std::string reason =
6212 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006213 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006214 ns2ms(currentWait),
6215 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006216 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006217 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006218
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006219 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6220
6221 // Stop waking up for events on this connection, it is already unresponsive
6222 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006223}
6224
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006225void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6226 std::string reason =
6227 StringPrintf("%s does not have a focused window", application->getName().c_str());
6228 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006229
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6231 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006232 mPolicy.notifyNoFocusedWindowAnr(application);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006233 };
6234 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006235}
6236
chaviw98318de2021-05-19 16:45:23 -05006237void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006238 const std::string& reason) {
6239 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6240 updateLastAnrStateLocked(windowLabel, reason);
6241}
6242
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006243void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6244 const std::string& reason) {
6245 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006246 updateLastAnrStateLocked(windowLabel, reason);
6247}
6248
6249void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6250 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006252 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253 struct tm tm;
6254 localtime_r(&t, &tm);
6255 char timestr[64];
6256 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006257 mLastAnrState.clear();
6258 mLastAnrState += INDENT "ANR:\n";
6259 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006260 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6261 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006262 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263}
6264
Prabir Pradhancef936d2021-07-21 16:17:52 +00006265void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6266 KeyEntry& entry) {
6267 const KeyEvent event = createKeyEvent(entry);
6268 nsecs_t delay = 0;
6269 { // release lock
6270 scoped_unlock unlock(mLock);
6271 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006272 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006273 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6274 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6275 std::to_string(t.duration().count()).c_str());
6276 }
6277 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278
6279 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006280 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006281 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006282 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006284 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006285 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287}
6288
Prabir Pradhancef936d2021-07-21 16:17:52 +00006289void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006290 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006291 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006292 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006294 mPolicy.notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006295 };
6296 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006297}
6298
Prabir Pradhanedd96402022-02-15 01:46:16 -08006299void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6300 std::optional<int32_t> pid) {
6301 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006303 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006304 };
6305 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006306}
6307
6308/**
6309 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6310 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6311 * command entry to the command queue.
6312 */
6313void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6314 std::string reason) {
6315 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006316 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006317 if (connection.monitor) {
6318 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6319 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006320 pid = findMonitorPidByTokenLocked(connectionToken);
6321 } else {
6322 // The connection is a window
6323 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6324 reason.c_str());
6325 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6326 if (handle != nullptr) {
6327 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006329 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006330 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006331}
6332
6333/**
6334 * Tell the policy that a connection has become responsive so that it can stop ANR.
6335 */
6336void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6337 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006338 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006339 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006340 pid = findMonitorPidByTokenLocked(connectionToken);
6341 } else {
6342 // The connection is a window
6343 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6344 if (handle != nullptr) {
6345 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006346 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006347 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006348 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006349}
6350
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006351bool InputDispatcher::afterKeyEventLockedInterruptable(
6352 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6353 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006354 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006355 if (!handled) {
6356 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006357 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006358 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006359 return false;
6360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006362 // Get the fallback key state.
6363 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006364 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006365 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006366 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006367 connection->inputState.removeFallbackKey(originalKeyCode);
6368 }
6369
6370 if (handled || !dispatchEntry->hasForegroundTarget()) {
6371 // If the application handles the original key for which we previously
6372 // generated a fallback or if the window is not a foreground window,
6373 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006374 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006375 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006376 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6377 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6378 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6379 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6380 keyEntry.policyFlags);
6381 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006382 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006383 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384
6385 mLock.unlock();
6386
Prabir Pradhana41d2442023-04-20 21:30:40 +00006387 if (const auto unhandledKeyFallback =
6388 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6389 event, keyEntry.policyFlags);
6390 unhandledKeyFallback) {
6391 event = *unhandledKeyFallback;
6392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393
6394 mLock.lock();
6395
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006396 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006397 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006398 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006399 "application handled the original non-fallback key "
6400 "or is no longer a foreground target, "
6401 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006402 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006405 connection->inputState.removeFallbackKey(originalKeyCode);
6406 }
6407 } else {
6408 // If the application did not handle a non-fallback key, first check
6409 // that we are in a good state to perform unhandled key event processing
6410 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006411 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006412 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006413 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6414 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6415 "since this is not an initial down. "
6416 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6417 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6418 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419 return false;
6420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006421
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006422 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006423 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6424 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6425 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6426 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6427 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006428 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006429
6430 mLock.unlock();
6431
Prabir Pradhana41d2442023-04-20 21:30:40 +00006432 bool fallback = false;
6433 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6434 event, keyEntry.policyFlags);
6435 fb) {
6436 fallback = true;
6437 event = *fb;
6438 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439
6440 mLock.lock();
6441
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006442 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006443 connection->inputState.removeFallbackKey(originalKeyCode);
6444 return false;
6445 }
6446
6447 // Latch the fallback keycode for this key on an initial down.
6448 // The fallback keycode cannot change at any other point in the lifecycle.
6449 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006450 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006451 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006453 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006455 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006456 }
6457
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006458 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006459
6460 // Cancel the fallback key if the policy decides not to send it anymore.
6461 // We will continue to dispatch the key to the policy but we will no
6462 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6464 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006465 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6466 if (fallback) {
6467 ALOGD("Unhandled key event: Policy requested to send key %d"
6468 "as a fallback for %d, but on the DOWN it had requested "
6469 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006470 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006471 } else {
6472 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6473 "but on the DOWN it had requested to send %d. "
6474 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006475 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006476 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006477 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006478
Michael Wrightfb04fd52022-11-24 22:31:11 +00006479 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006481 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006482 synthesizeCancelationEventsForConnectionLocked(connection, options);
6483
6484 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006485 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006486 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006487 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488 }
6489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006490
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006491 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6492 {
6493 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006495 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006496 for (const auto& [key, value] : fallbackKeys) {
6497 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006498 }
6499 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6500 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006502 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503
6504 if (fallback) {
6505 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006506 keyEntry.eventTime = event.getEventTime();
6507 keyEntry.deviceId = event.getDeviceId();
6508 keyEntry.source = event.getSource();
6509 keyEntry.displayId = event.getDisplayId();
6510 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006511 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006512 keyEntry.scanCode = event.getScanCode();
6513 keyEntry.metaState = event.getMetaState();
6514 keyEntry.repeatCount = event.getRepeatCount();
6515 keyEntry.downTime = event.getDownTime();
6516 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006518 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6519 ALOGD("Unhandled key event: Dispatching fallback key. "
6520 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006521 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006522 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006523 return true; // restart the event
6524 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006525 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6526 ALOGD("Unhandled key event: No fallback key.");
6527 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006528
6529 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006530 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531 }
6532 }
6533 return false;
6534}
6535
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006536bool InputDispatcher::afterMotionEventLockedInterruptable(
6537 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6538 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539 return false;
6540}
6541
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542void InputDispatcher::traceInboundQueueLengthLocked() {
6543 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006544 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545 }
6546}
6547
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006548void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006549 if (ATRACE_ENABLED()) {
6550 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006551 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6552 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553 }
6554}
6555
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006556void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 if (ATRACE_ENABLED()) {
6558 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006559 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6560 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006561 }
6562}
6563
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006564void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006565 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006567 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006568 dumpDispatchStateLocked(dump);
6569
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006570 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006571 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006572 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 }
6574}
6575
6576void InputDispatcher::monitor() {
6577 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006578 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006580 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581}
6582
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006583/**
6584 * Wake up the dispatcher and wait until it processes all events and commands.
6585 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6586 * this method can be safely called from any thread, as long as you've ensured that
6587 * the work you are interested in completing has already been queued.
6588 */
6589bool InputDispatcher::waitForIdle() {
6590 /**
6591 * Timeout should represent the longest possible time that a device might spend processing
6592 * events and commands.
6593 */
6594 constexpr std::chrono::duration TIMEOUT = 100ms;
6595 std::unique_lock lock(mLock);
6596 mLooper->wake();
6597 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6598 return result == std::cv_status::no_timeout;
6599}
6600
Vishnu Naire798b472020-07-23 13:52:21 -07006601/**
6602 * Sets focus to the window identified by the token. This must be called
6603 * after updating any input window handles.
6604 *
6605 * Params:
6606 * request.token - input channel token used to identify the window that should gain focus.
6607 * request.focusedToken - the token that the caller expects currently to be focused. If the
6608 * specified token does not match the currently focused window, this request will be dropped.
6609 * If the specified focused token matches the currently focused window, the call will succeed.
6610 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6611 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6612 * when requesting the focus change. This determines which request gets
6613 * precedence if there is a focus change request from another source such as pointer down.
6614 */
Vishnu Nair958da932020-08-21 17:12:37 -07006615void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6616 { // acquire lock
6617 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006618 std::optional<FocusResolver::FocusChanges> changes =
6619 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6620 if (changes) {
6621 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006622 }
6623 } // release lock
6624 // Wake up poll loop since it may need to make new input dispatching choices.
6625 mLooper->wake();
6626}
6627
Vishnu Nairc519ff72021-01-21 08:23:08 -08006628void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6629 if (changes.oldFocus) {
6630 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006631 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006632 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006633 "focus left window");
6634 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006635 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006636 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006637 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006638 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006639 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006640 }
6641
Prabir Pradhan99987712020-11-10 18:43:05 -08006642 // If a window has pointer capture, then it must have focus. We need to ensure that this
6643 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6644 // If the window loses focus before it loses pointer capture, then the window can be in a state
6645 // where it has pointer capture but not focus, violating the contract. Therefore we must
6646 // dispatch the pointer capture event before the focus event. Since focus events are added to
6647 // the front of the queue (above), we add the pointer capture event to the front of the queue
6648 // after the focus events are added. This ensures the pointer capture event ends up at the
6649 // front.
6650 disablePointerCaptureForcedLocked();
6651
Vishnu Nairc519ff72021-01-21 08:23:08 -08006652 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006653 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006654 }
6655}
Vishnu Nair958da932020-08-21 17:12:37 -07006656
Prabir Pradhan99987712020-11-10 18:43:05 -08006657void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006658 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006659 return;
6660 }
6661
6662 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6663
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006664 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006665 setPointerCaptureLocked(false);
6666 }
6667
6668 if (!mWindowTokenWithPointerCapture) {
6669 // No need to send capture changes because no window has capture.
6670 return;
6671 }
6672
6673 if (mPendingEvent != nullptr) {
6674 // Move the pending event to the front of the queue. This will give the chance
6675 // for the pending event to be dropped if it is a captured event.
6676 mInboundQueue.push_front(mPendingEvent);
6677 mPendingEvent = nullptr;
6678 }
6679
6680 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006681 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006682 mInboundQueue.push_front(std::move(entry));
6683}
6684
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006685void InputDispatcher::setPointerCaptureLocked(bool enable) {
6686 mCurrentPointerCaptureRequest.enable = enable;
6687 mCurrentPointerCaptureRequest.seq++;
6688 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006689 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006690 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006691 };
6692 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006693}
6694
Vishnu Nair599f1412021-06-21 10:39:58 -07006695void InputDispatcher::displayRemoved(int32_t displayId) {
6696 { // acquire lock
6697 std::scoped_lock _l(mLock);
6698 // Set an empty list to remove all handles from the specific display.
6699 setInputWindowsLocked(/* window handles */ {}, displayId);
6700 setFocusedApplicationLocked(displayId, nullptr);
6701 // Call focus resolver to clean up stale requests. This must be called after input windows
6702 // have been removed for the removed display.
6703 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006704 // Reset pointer capture eligibility, regardless of previous state.
6705 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006706 // Remove the associated touch mode state.
6707 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006708 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006709 } // release lock
6710
6711 // Wake up poll loop since it may need to make new input dispatching choices.
6712 mLooper->wake();
6713}
6714
Patrick Williamsd828f302023-04-28 17:52:08 -05006715void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006716 // The listener sends the windows as a flattened array. Separate the windows by display for
6717 // more convenient parsing.
6718 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006719 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006720 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006721 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006722 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006723
6724 { // acquire lock
6725 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006726
6727 // Ensure that we have an entry created for all existing displays so that if a displayId has
6728 // no windows, we can tell that the windows were removed from the display.
6729 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6730 handlesPerDisplay[displayId];
6731 }
6732
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006733 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006734 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006735 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6736 }
6737
6738 for (const auto& [displayId, handles] : handlesPerDisplay) {
6739 setInputWindowsLocked(handles, displayId);
6740 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006741
6742 if (update.vsyncId < mWindowInfosVsyncId) {
6743 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6744 ", current update vsync id: %" PRId64,
6745 mWindowInfosVsyncId, update.vsyncId);
6746 }
6747 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006748 }
6749 // Wake up poll loop since it may need to make new input dispatching choices.
6750 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006751}
6752
Vishnu Nair062a8672021-09-03 16:07:44 -07006753bool InputDispatcher::shouldDropInput(
6754 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006755 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6756 (windowHandle->getInfo()->inputConfig.test(
6757 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006758 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006759 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6760 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006761 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006762 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006763 windowHandle->getInfo()->displayId);
6764 return true;
6765 }
6766 return false;
6767}
6768
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006769void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006770 const gui::WindowInfosUpdate& update) {
6771 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006772}
6773
Arthur Hungdfd528e2021-12-08 13:23:04 +00006774void InputDispatcher::cancelCurrentTouch() {
6775 {
6776 std::scoped_lock _l(mLock);
6777 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006778 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006779 "cancel current touch");
6780 synthesizeCancelationEventsForAllConnectionsLocked(options);
6781
6782 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006783 }
6784 // Wake up poll loop since there might be work to do.
6785 mLooper->wake();
6786}
6787
Prabir Pradhan87112a72023-04-20 19:13:39 +00006788void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006789 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006790
6791 std::scoped_lock _l(mLock);
6792 mConfig = config;
6793}
6794
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006795void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6796 std::scoped_lock _l(mLock);
6797 mMonitorDispatchingTimeout = timeout;
6798}
6799
Arthur Hungc539dbb2022-12-08 07:45:36 +00006800void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6801 const sp<WindowInfoHandle>& oldWindowHandle,
6802 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006803 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006804 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006805 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6806 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006807 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6808 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6809 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6810 newWindowHandle->getInfo()->inputConfig.test(
6811 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6812 const sp<WindowInfoHandle> oldWallpaper =
6813 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6814 const sp<WindowInfoHandle> newWallpaper =
6815 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6816 if (oldWallpaper == newWallpaper) {
6817 return;
6818 }
6819
6820 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006821 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6822 addWindowTargetLocked(oldWallpaper,
6823 oldTouchedWindow.targetFlags |
6824 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6825 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6826 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006827 }
6828
6829 if (newWallpaper != nullptr) {
6830 state.addOrUpdateWindow(newWallpaper,
6831 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6832 InputTarget::Flags::WINDOW_IS_OBSCURED |
6833 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6834 pointerIds);
6835 }
6836}
6837
6838void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6839 ftl::Flags<InputTarget::Flags> newTargetFlags,
6840 const sp<WindowInfoHandle> fromWindowHandle,
6841 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006842 TouchState& state,
6843 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006844 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6845 fromWindowHandle->getInfo()->inputConfig.test(
6846 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6847 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6848 toWindowHandle->getInfo()->inputConfig.test(
6849 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6850
6851 const sp<WindowInfoHandle> oldWallpaper =
6852 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6853 const sp<WindowInfoHandle> newWallpaper =
6854 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6855 if (oldWallpaper == newWallpaper) {
6856 return;
6857 }
6858
6859 if (oldWallpaper != nullptr) {
6860 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6861 "transferring touch focus to another window");
6862 state.removeWindowByToken(oldWallpaper->getToken());
6863 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6864 }
6865
6866 if (newWallpaper != nullptr) {
6867 nsecs_t downTimeInTarget = now();
6868 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6869 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6870 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6871 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6872 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006873 std::shared_ptr<Connection> wallpaperConnection =
6874 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006875 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006876 std::shared_ptr<Connection> toConnection =
6877 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006878 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6879 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6880 wallpaperFlags);
6881 }
6882 }
6883}
6884
6885sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6886 const sp<WindowInfoHandle>& windowHandle) const {
6887 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6888 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6889 bool foundWindow = false;
6890 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6891 if (!foundWindow && otherHandle != windowHandle) {
6892 continue;
6893 }
6894 if (windowHandle == otherHandle) {
6895 foundWindow = true;
6896 continue;
6897 }
6898
6899 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6900 return otherHandle;
6901 }
6902 }
6903 return nullptr;
6904}
6905
Garfield Tane84e6f92019-08-29 17:28:41 -07006906} // namespace android::inputdispatcher