blob: 1c1a0bbb377d252db5fc74d87bcfd1d58f787617 [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);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004328 for (uint32_t i = 0; i < args.getPointerCount(); 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 Vishniakou3218fc02023-06-15 20:41:02 -07004345 Result<void> motionCheck =
4346 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4347 args.pointerProperties.data());
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004348 if (!motionCheck.ok()) {
4349 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004350 return;
4351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004353 if (DEBUG_VERIFY_EVENTS) {
4354 auto [it, _] =
4355 mVerifiersByDisplay.try_emplace(args.displayId,
4356 StringPrintf("display %" PRId32, args.displayId));
4357 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004358 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4359 args.pointerProperties.data(), args.pointerCoords.data(),
4360 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004361 if (!result.ok()) {
4362 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4363 }
4364 }
4365
Prabir Pradhan678438e2023-04-13 19:32:51 +00004366 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004368
4369 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004370 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004371 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4372 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004373 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
Antonio Kantekf16f2832021-09-28 04:39:20 +00004376 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 { // acquire lock
4378 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004379 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4380 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4381 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004382 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004383 if (touchStateIt != mTouchStatesByDisplay.end()) {
4384 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004385 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004386 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4387 }
4388 }
4389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
4391 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004392 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004393 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004394 displayTransform = it->second.transform;
4395 }
4396
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 mLock.unlock();
4398
4399 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004400 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4401 args.action, args.actionButton, args.flags, args.edgeFlags,
4402 args.metaState, args.buttonState, args.classification,
4403 displayTransform, args.xPrecision, args.yPrecision,
4404 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004405 args.downTime, args.eventTime, args.getPointerCount(),
4406 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407
4408 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004409 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 return; // event was consumed by the filter
4411 }
4412
4413 mLock.lock();
4414 }
4415
4416 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004417 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004418 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4419 args.displayId, policyFlags, args.action,
4420 args.actionButton, args.flags, args.metaState,
4421 args.buttonState, args.classification, args.edgeFlags,
4422 args.xPrecision, args.yPrecision,
4423 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004424 args.downTime, args.getPointerCount(),
4425 args.pointerProperties.data(),
4426 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427
Prabir Pradhan678438e2023-04-13 19:32:51 +00004428 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4429 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004430 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004431 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4432 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004433 }
4434
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004435 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 mLock.unlock();
4437 } // release lock
4438
4439 if (needWake) {
4440 mLooper->wake();
4441 }
4442}
4443
Prabir Pradhan678438e2023-04-13 19:32:51 +00004444void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004445 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004446 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4447 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004448 args.id, args.eventTime, args.deviceId, args.source,
4449 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004450 }
Chris Yef59a2f42020-10-16 12:55:26 -07004451
Antonio Kantekf16f2832021-09-28 04:39:20 +00004452 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004453 { // acquire lock
4454 mLock.lock();
4455
4456 // Just enqueue a new sensor event.
4457 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004458 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4459 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4460 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004461
4462 needWake = enqueueInboundEventLocked(std::move(newEntry));
4463 mLock.unlock();
4464 } // release lock
4465
4466 if (needWake) {
4467 mLooper->wake();
4468 }
4469}
4470
Prabir Pradhan678438e2023-04-13 19:32:51 +00004471void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004472 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004473 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4474 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004475 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004476 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004477}
4478
Prabir Pradhan678438e2023-04-13 19:32:51 +00004479bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004480 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481}
4482
Prabir Pradhan678438e2023-04-13 19:32:51 +00004483void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004484 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004485 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4486 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004487 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489
Prabir Pradhan678438e2023-04-13 19:32:51 +00004490 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004492 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493}
4494
Prabir Pradhan678438e2023-04-13 19:32:51 +00004495void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004496 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004497 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4498 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500
Antonio Kantekf16f2832021-09-28 04:39:20 +00004501 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004503 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004505 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004506 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004507 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 } // release lock
4509
4510 if (needWake) {
4511 mLooper->wake();
4512 }
4513}
4514
Prabir Pradhan678438e2023-04-13 19:32:51 +00004515void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004516 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004517 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4518 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004519 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004520
Antonio Kantekf16f2832021-09-28 04:39:20 +00004521 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004522 { // acquire lock
4523 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004524 auto entry =
4525 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004526 needWake = enqueueInboundEventLocked(std::move(entry));
4527 } // release lock
4528
4529 if (needWake) {
4530 mLooper->wake();
4531 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004532}
4533
Prabir Pradhan5735a322022-04-11 17:23:34 +00004534InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4535 std::optional<int32_t> targetUid,
4536 InputEventInjectionSync syncMode,
4537 std::chrono::milliseconds timeout,
4538 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004539 Result<void> eventValidation = validateInputEvent(*event);
4540 if (!eventValidation.ok()) {
4541 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4542 return InputEventInjectionResult::FAILED;
4543 }
4544
Prabir Pradhan65613802023-02-22 23:36:58 +00004545 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004546 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4547 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4548 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4549 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004550 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004551 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Prabir Pradhan5735a322022-04-11 17:23:34 +00004553 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004555 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004556 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4557 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4558 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4559 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4560 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004561 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004562 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004563 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004564 }
4565
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004566 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004568 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004569 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004570 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004571 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004572 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4573 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4574 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004575 int32_t keyCode = incomingKey.getKeyCode();
4576 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004577 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004578 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004579 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004580 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004581 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4582 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4583 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4586 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004587 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004588
4589 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4590 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004591 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4593 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4594 std::to_string(t.duration().count()).c_str());
4595 }
4596 }
4597
4598 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004599 std::unique_ptr<KeyEntry> injectedEntry =
4600 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004601 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004602 incomingKey.getDisplayId(), policyFlags, action,
4603 flags, keyCode, incomingKey.getScanCode(), metaState,
4604 incomingKey.getRepeatCount(),
4605 incomingKey.getDownTime());
4606 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004607 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 }
4609
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004610 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004611 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004612 const bool isPointerEvent =
4613 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4614 // If a pointer event has no displayId specified, inject it to the default display.
4615 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4616 ? ADISPLAY_ID_DEFAULT
4617 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004618 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004619
4620 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004621 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004623 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004624 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4625 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4626 std::to_string(t.duration().count()).c_str());
4627 }
4628 }
4629
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004630 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4631 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4632 }
4633
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004634 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004635 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4636 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004637 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004638 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4639 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004640 displayId, policyFlags, motionEvent.getAction(),
4641 motionEvent.getActionButton(), flags,
4642 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004643 motionEvent.getButtonState(),
4644 motionEvent.getClassification(),
4645 motionEvent.getEdgeFlags(),
4646 motionEvent.getXPrecision(),
4647 motionEvent.getYPrecision(),
4648 motionEvent.getRawXCursorPosition(),
4649 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004650 motionEvent.getDownTime(),
4651 motionEvent.getPointerCount(),
4652 motionEvent.getPointerProperties(),
4653 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004654 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004655 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004656 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004657 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004658 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004659 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004660 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4661 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004662 displayId, policyFlags,
4663 motionEvent.getAction(),
4664 motionEvent.getActionButton(), flags,
4665 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004666 motionEvent.getButtonState(),
4667 motionEvent.getClassification(),
4668 motionEvent.getEdgeFlags(),
4669 motionEvent.getXPrecision(),
4670 motionEvent.getYPrecision(),
4671 motionEvent.getRawXCursorPosition(),
4672 motionEvent.getRawYCursorPosition(),
4673 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004674 motionEvent.getPointerCount(),
4675 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004676 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004677 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4678 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004679 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680 }
4681 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004685 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004686 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 }
4688
Prabir Pradhan5735a322022-04-11 17:23:34 +00004689 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004690 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691 injectionState->injectionIsAsync = true;
4692 }
4693
4694 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004695 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
4697 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004698 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004699 if (DEBUG_INJECTION) {
4700 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4701 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004702 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004703 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 }
4705
4706 mLock.unlock();
4707
4708 if (needWake) {
4709 mLooper->wake();
4710 }
4711
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004712 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004714 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 if (syncMode == InputEventInjectionSync::NONE) {
4717 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 } else {
4719 for (;;) {
4720 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004721 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 break;
4723 }
4724
4725 nsecs_t remainingTimeout = endTime - now();
4726 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004727 if (DEBUG_INJECTION) {
4728 ALOGD("injectInputEvent - Timed out waiting for injection result "
4729 "to become available.");
4730 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004731 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 break;
4733 }
4734
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004735 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 }
4737
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004738 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4739 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004741 if (DEBUG_INJECTION) {
4742 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4743 injectionState->pendingForegroundDispatches);
4744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 nsecs_t remainingTimeout = endTime - now();
4746 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004747 if (DEBUG_INJECTION) {
4748 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4749 "dispatches to finish.");
4750 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004751 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 break;
4753 }
4754
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004755 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
4757 }
4758 }
4759
4760 injectionState->release();
4761 } // release lock
4762
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004763 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004764 LOG(DEBUG) << "injectInputEvent - Finished with result "
4765 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
4768 return injectionResult;
4769}
4770
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004771std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004772 std::array<uint8_t, 32> calculatedHmac;
4773 std::unique_ptr<VerifiedInputEvent> result;
4774 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004775 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004776 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4777 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4778 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004779 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004780 break;
4781 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004782 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004783 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4784 VerifiedMotionEvent verifiedMotionEvent =
4785 verifiedMotionEventFromMotionEvent(motionEvent);
4786 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004787 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004788 break;
4789 }
4790 default: {
4791 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4792 return nullptr;
4793 }
4794 }
4795 if (calculatedHmac == INVALID_HMAC) {
4796 return nullptr;
4797 }
tyiu1573a672023-02-21 22:38:32 +00004798 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004799 return nullptr;
4800 }
4801 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004802}
4803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004804void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004806 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004808 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004809 LOG(DEBUG) << "Setting input event injection result to "
4810 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004813 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 // Log the outcome since the injector did not wait for the injection result.
4815 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004817 ALOGV("Asynchronous input event injection succeeded.");
4818 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004819 case InputEventInjectionResult::TARGET_MISMATCH:
4820 ALOGV("Asynchronous input event injection target mismatch.");
4821 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004822 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823 ALOGW("Asynchronous input event injection failed.");
4824 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004825 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 ALOGW("Asynchronous input event injection timed out.");
4827 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004828 case InputEventInjectionResult::PENDING:
4829 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4830 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832 }
4833
4834 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004835 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 }
4837}
4838
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004839void InputDispatcher::transformMotionEntryForInjectionLocked(
4840 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004841 // Input injection works in the logical display coordinate space, but the input pipeline works
4842 // display space, so we need to transform the injected events accordingly.
4843 const auto it = mDisplayInfos.find(entry.displayId);
4844 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004845 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004846
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004847 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4848 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4849 const vec2 cursor =
4850 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4851 {entry.xCursorPosition, entry.yCursorPosition});
4852 entry.xCursorPosition = cursor.x;
4853 entry.yCursorPosition = cursor.y;
4854 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004855 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004856 entry.pointerCoords[i] =
4857 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4858 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004859 }
4860}
4861
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004862void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4863 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 if (injectionState) {
4865 injectionState->pendingForegroundDispatches += 1;
4866 }
4867}
4868
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004869void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4870 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 if (injectionState) {
4872 injectionState->pendingForegroundDispatches -= 1;
4873
4874 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004875 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877 }
4878}
4879
chaviw98318de2021-05-19 16:45:23 -05004880const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004881 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004882 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004883 auto it = mWindowHandlesByDisplay.find(displayId);
4884 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004885}
4886
chaviw98318de2021-05-19 16:45:23 -05004887sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004888 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004889 if (windowHandleToken == nullptr) {
4890 return nullptr;
4891 }
4892
Arthur Hungb92218b2018-08-14 12:00:21 +08004893 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004894 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4895 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004896 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004897 return windowHandle;
4898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 }
4900 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004901 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902}
4903
chaviw98318de2021-05-19 16:45:23 -05004904sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4905 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004906 if (windowHandleToken == nullptr) {
4907 return nullptr;
4908 }
4909
chaviw98318de2021-05-19 16:45:23 -05004910 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004911 if (windowHandle->getToken() == windowHandleToken) {
4912 return windowHandle;
4913 }
4914 }
4915 return nullptr;
4916}
4917
chaviw98318de2021-05-19 16:45:23 -05004918sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4919 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004920 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004921 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4922 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004923 if (handle->getId() == windowHandle->getId() &&
4924 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004925 if (windowHandle->getInfo()->displayId != it.first) {
4926 ALOGE("Found window %s in display %" PRId32
4927 ", but it should belong to display %" PRId32,
4928 windowHandle->getName().c_str(), it.first,
4929 windowHandle->getInfo()->displayId);
4930 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004931 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 }
4934 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004935 return nullptr;
4936}
4937
chaviw98318de2021-05-19 16:45:23 -05004938sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004939 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4940 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941}
4942
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004943ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4944 auto displayInfoIt = mDisplayInfos.find(displayId);
4945 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4946 : kIdentityTransform;
4947}
4948
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004949bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4950 const MotionEntry& motionEntry) const {
4951 const WindowInfo& info = *window->getInfo();
4952
4953 // Skip spy window targets that are not valid for targeted injection.
4954 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004955 return false;
4956 }
4957
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004958 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4959 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4960 return false;
4961 }
4962
4963 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4964 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4965 window->getName().c_str());
4966 return false;
4967 }
4968
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004969 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004970 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004971 ALOGW("Not sending touch to %s because there's no corresponding connection",
4972 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004973 return false;
4974 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004975
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004976 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004977 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004978 return false;
4979 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004980
4981 // Drop events that can't be trusted due to occlusion
4982 const auto [x, y] = resolveTouchedPosition(motionEntry);
4983 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4984 if (!isTouchTrustedLocked(occlusionInfo)) {
4985 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004986 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004987 for (const auto& log : occlusionInfo.debugInfo) {
4988 ALOGD("%s", log.c_str());
4989 }
4990 }
4991 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4992 occlusionInfo.obscuringUid);
4993 return false;
4994 }
4995
4996 // Drop touch events if requested by input feature
4997 if (shouldDropInput(motionEntry, window)) {
4998 return false;
4999 }
5000
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005001 return true;
5002}
5003
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005004std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5005 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005006 auto connectionIt = mConnectionsByToken.find(token);
5007 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005008 return nullptr;
5009 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005010 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005011}
5012
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005013void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005014 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5015 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005016 // Remove all handles on a display if there are no windows left.
5017 mWindowHandlesByDisplay.erase(displayId);
5018 return;
5019 }
5020
5021 // Since we compare the pointer of input window handles across window updates, we need
5022 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005023 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5024 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5025 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005026 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005027 }
5028
chaviw98318de2021-05-19 16:45:23 -05005029 std::vector<sp<WindowInfoHandle>> newHandles;
5030 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005031 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005032 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005033 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005034 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005035 const bool canReceiveInput =
5036 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5037 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005038 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005039 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005040 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005041 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005042 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005043 }
5044
5045 if (info->displayId != displayId) {
5046 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5047 handle->getName().c_str(), displayId, info->displayId);
5048 continue;
5049 }
5050
Robert Carredd13602020-04-13 17:24:34 -07005051 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5052 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005053 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005054 oldHandle->updateFrom(handle);
5055 newHandles.push_back(oldHandle);
5056 } else {
5057 newHandles.push_back(handle);
5058 }
5059 }
5060
5061 // Insert or replace
5062 mWindowHandlesByDisplay[displayId] = newHandles;
5063}
5064
Arthur Hung72d8dc32020-03-28 00:48:39 +00005065void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005066 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005067 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005068 { // acquire lock
5069 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005070 for (const auto& [displayId, handles] : handlesPerDisplay) {
5071 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005072 }
5073 }
5074 // Wake up poll loop since it may need to make new input dispatching choices.
5075 mLooper->wake();
5076}
5077
Arthur Hungb92218b2018-08-14 12:00:21 +08005078/**
5079 * Called from InputManagerService, update window handle list by displayId that can receive input.
5080 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5081 * If set an empty list, remove all handles from the specific display.
5082 * For focused handle, check if need to change and send a cancel event to previous one.
5083 * For removed handle, check if need to send a cancel event if already in touch.
5084 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005085void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005086 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005087 if (DEBUG_FOCUS) {
5088 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005089 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 windowList += iwh->getName() + " ";
5091 }
5092 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094
Prabir Pradhand65552b2021-10-07 11:23:50 -07005095 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005096 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005097 const WindowInfo& info = *window->getInfo();
5098
5099 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005100 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005101 if (noInputWindow && window->getToken() != nullptr) {
5102 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5103 window->getName().c_str());
5104 window->releaseChannel();
5105 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005106
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005107 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005108 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5109 !info.inputConfig.test(
5110 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005111 "%s has feature SPY, but is not a trusted overlay.",
5112 window->getName().c_str());
5113
Prabir Pradhand65552b2021-10-07 11:23:50 -07005114 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005115 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5116 !info.inputConfig.test(
5117 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005118 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5119 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005120 }
5121
Arthur Hung72d8dc32020-03-28 00:48:39 +00005122 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005123 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005125 // Save the old windows' orientation by ID before it gets updated.
5126 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005127 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005128 oldWindowOrientations.emplace(handle->getId(),
5129 handle->getInfo()->transform.getOrientation());
5130 }
5131
chaviw98318de2021-05-19 16:45:23 -05005132 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005133
chaviw98318de2021-05-19 16:45:23 -05005134 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005135
Vishnu Nairc519ff72021-01-21 08:23:08 -08005136 std::optional<FocusResolver::FocusChanges> changes =
5137 mFocusResolver.setInputWindows(displayId, windowHandles);
5138 if (changes) {
5139 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005142 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5143 mTouchStatesByDisplay.find(displayId);
5144 if (stateIt != mTouchStatesByDisplay.end()) {
5145 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005146 for (size_t i = 0; i < state.windows.size();) {
5147 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005148 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005150 ALOGD("Touched window was removed: %s in display %" PRId32,
5151 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005152 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005153 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005154 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5155 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005156 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005157 "touched window was removed");
5158 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005159 // Since we are about to drop the touch, cancel the events for the wallpaper as
5160 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005161 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005162 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5163 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005164 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005165 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005168 state.windows.erase(state.windows.begin() + i);
5169 } else {
5170 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 }
5172 }
arthurhungb89ccb02020-12-30 16:19:01 +08005173
arthurhung6d4bed92021-03-17 11:59:33 +08005174 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005175 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005176 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005177 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005178 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005179 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5180 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005181 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005182 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005183 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005184
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005185 // Determine if the orientation of any of the input windows have changed, and cancel all
5186 // pointer events if necessary.
5187 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5188 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5189 if (newWindowHandle != nullptr &&
5190 newWindowHandle->getInfo()->transform.getOrientation() !=
5191 oldWindowOrientations[oldWindowHandle->getId()]) {
5192 std::shared_ptr<InputChannel> inputChannel =
5193 getInputChannelLocked(newWindowHandle->getToken());
5194 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005195 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005196 "touched window's orientation changed");
5197 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005198 }
5199 }
5200 }
5201
Arthur Hung72d8dc32020-03-28 00:48:39 +00005202 // Release information for windows that are no longer present.
5203 // This ensures that unused input channels are released promptly.
5204 // Otherwise, they might stick around until the window handle is destroyed
5205 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005206 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005207 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005208 if (DEBUG_FOCUS) {
5209 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005210 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005211 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005212 }
chaviw291d88a2019-02-14 10:33:58 -08005213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214}
5215
5216void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005217 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005218 if (DEBUG_FOCUS) {
5219 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5220 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5221 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005222 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005223 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005224 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 } // release lock
5226
5227 // Wake up poll loop since it may need to make new input dispatching choices.
5228 mLooper->wake();
5229}
5230
Vishnu Nair599f1412021-06-21 10:39:58 -07005231void InputDispatcher::setFocusedApplicationLocked(
5232 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5233 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5234 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5235
5236 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5237 return; // This application is already focused. No need to wake up or change anything.
5238 }
5239
5240 // Set the new application handle.
5241 if (inputApplicationHandle != nullptr) {
5242 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5243 } else {
5244 mFocusedApplicationHandlesByDisplay.erase(displayId);
5245 }
5246
5247 // No matter what the old focused application was, stop waiting on it because it is
5248 // no longer focused.
5249 resetNoFocusedWindowTimeoutLocked();
5250}
5251
Tiger Huang721e26f2018-07-24 22:26:19 +08005252/**
5253 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5254 * the display not specified.
5255 *
5256 * We track any unreleased events for each window. If a window loses the ability to receive the
5257 * released event, we will send a cancel event to it. So when the focused display is changed, we
5258 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5259 * display. The display-specified events won't be affected.
5260 */
5261void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005262 if (DEBUG_FOCUS) {
5263 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5264 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005266 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005267
5268 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005269 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005270 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005271 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005272 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005273 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005274 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005275 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005276 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005277 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005278 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005279 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5280 }
5281 }
5282 mFocusedDisplayId = displayId;
5283
Chris Ye3c2d6f52020-08-09 10:39:48 -07005284 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005285 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005286 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005287
Vishnu Nairad321cd2020-08-20 16:40:21 -07005288 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005289 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005290 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005291 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005292 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005293 }
5294 }
5295 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005296 } // release lock
5297
5298 // Wake up poll loop since it may need to make new input dispatching choices.
5299 mLooper->wake();
5300}
5301
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005303 if (DEBUG_FOCUS) {
5304 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306
5307 bool changed;
5308 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005309 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310
5311 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5312 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005313 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 }
5315
5316 if (mDispatchEnabled && !enabled) {
5317 resetAndDropEverythingLocked("dispatcher is being disabled");
5318 }
5319
5320 mDispatchEnabled = enabled;
5321 mDispatchFrozen = frozen;
5322 changed = true;
5323 } else {
5324 changed = false;
5325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 } // release lock
5327
5328 if (changed) {
5329 // Wake up poll loop since it may need to make new input dispatching choices.
5330 mLooper->wake();
5331 }
5332}
5333
5334void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005335 if (DEBUG_FOCUS) {
5336 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338
5339 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005340 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341
5342 if (mInputFilterEnabled == enabled) {
5343 return;
5344 }
5345
5346 mInputFilterEnabled = enabled;
5347 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5348 } // release lock
5349
5350 // Wake up poll loop since there might be work to do to drop everything.
5351 mLooper->wake();
5352}
5353
Antonio Kanteka042c022022-07-06 16:51:07 -07005354bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5355 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005356 bool needWake = false;
5357 {
5358 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005359 ALOGD_IF(DEBUG_TOUCH_MODE,
5360 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5361 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5362 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5363 mTouchModePerDisplay.count(displayId) == 0
5364 ? "not set"
5365 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5366
Antonio Kantek15beb512022-06-13 22:35:41 +00005367 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5368 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005369 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005370 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005371 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005372 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5373 !recentWindowsAreOwnedByLocked(pid, uid)) {
5374 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5375 "window nor none of the previously interacted window",
5376 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005377 return false;
5378 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005379 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005380 mTouchModePerDisplay[displayId] = inTouchMode;
5381 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5382 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005383 needWake = enqueueInboundEventLocked(std::move(entry));
5384 } // release lock
5385
5386 if (needWake) {
5387 mLooper->wake();
5388 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005389 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005390}
5391
Antonio Kantek48710e42022-03-24 14:19:30 -07005392bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5393 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5394 if (focusedToken == nullptr) {
5395 return false;
5396 }
5397 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5398 return isWindowOwnedBy(windowHandle, pid, uid);
5399}
5400
5401bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5402 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5403 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5404 const sp<WindowInfoHandle> windowHandle =
5405 getWindowHandleLocked(connectionToken);
5406 return isWindowOwnedBy(windowHandle, pid, uid);
5407 }) != mInteractionConnectionTokens.end();
5408}
5409
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005410void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5411 if (opacity < 0 || opacity > 1) {
5412 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5413 return;
5414 }
5415
5416 std::scoped_lock lock(mLock);
5417 mMaximumObscuringOpacityForTouch = opacity;
5418}
5419
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005420std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5421InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005422 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5423 for (TouchedWindow& w : state.windows) {
5424 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005425 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005426 }
5427 }
5428 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005429 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005430}
5431
arthurhungb89ccb02020-12-30 16:19:01 +08005432bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5433 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005434 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005435 if (DEBUG_FOCUS) {
5436 ALOGD("Trivial transfer to same window.");
5437 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005438 return true;
5439 }
5440
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005442 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443
Arthur Hungabbb9d82021-09-01 14:52:30 +00005444 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005445 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005446 if (state == nullptr || touchedWindow == nullptr) {
5447 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 return false;
5449 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005450
Arthur Hungabbb9d82021-09-01 14:52:30 +00005451 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5452 if (toWindowHandle == nullptr) {
5453 ALOGW("Cannot transfer focus because to window not found.");
5454 return false;
5455 }
5456
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005457 if (DEBUG_FOCUS) {
5458 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 touchedWindow->windowHandle->getName().c_str(),
5460 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 }
5462
Arthur Hungabbb9d82021-09-01 14:52:30 +00005463 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005464 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005465 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005466 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005467 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468
Arthur Hungabbb9d82021-09-01 14:52:30 +00005469 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005470 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005471 ftl::Flags<InputTarget::Flags> newTargetFlags =
5472 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005473 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005474 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005475 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005476 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477
Arthur Hungabbb9d82021-09-01 14:52:30 +00005478 // Store the dragging window.
5479 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005480 if (pointerIds.count() != 1) {
5481 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5482 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005483 return false;
5484 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005485 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005486 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005487 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 }
5489
Arthur Hungabbb9d82021-09-01 14:52:30 +00005490 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005491 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5492 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005493 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005494 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005495 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005496 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005497 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005499 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5500 newTargetFlags);
5501
5502 // Check if the wallpaper window should deliver the corresponding event.
5503 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5504 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 } // release lock
5507
5508 // Wake up poll loop since it may need to make new input dispatching choices.
5509 mLooper->wake();
5510 return true;
5511}
5512
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005513/**
5514 * Get the touched foreground window on the given display.
5515 * Return null if there are no windows touched on that display, or if more than one foreground
5516 * window is being touched.
5517 */
5518sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5519 auto stateIt = mTouchStatesByDisplay.find(displayId);
5520 if (stateIt == mTouchStatesByDisplay.end()) {
5521 ALOGI("No touch state on display %" PRId32, displayId);
5522 return nullptr;
5523 }
5524
5525 const TouchState& state = stateIt->second;
5526 sp<WindowInfoHandle> touchedForegroundWindow;
5527 // If multiple foreground windows are touched, return nullptr
5528 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005529 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005530 if (touchedForegroundWindow != nullptr) {
5531 ALOGI("Two or more foreground windows: %s and %s",
5532 touchedForegroundWindow->getName().c_str(),
5533 window.windowHandle->getName().c_str());
5534 return nullptr;
5535 }
5536 touchedForegroundWindow = window.windowHandle;
5537 }
5538 }
5539 return touchedForegroundWindow;
5540}
5541
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005542// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005543bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005544 sp<IBinder> fromToken;
5545 { // acquire lock
5546 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005547 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005548 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005549 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5550 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005551 return false;
5552 }
5553
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005554 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5555 if (from == nullptr) {
5556 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5557 return false;
5558 }
5559
5560 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005561 } // release lock
5562
5563 return transferTouchFocus(fromToken, destChannelToken);
5564}
5565
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005567 if (DEBUG_FOCUS) {
5568 ALOGD("Resetting and dropping all events (%s).", reason);
5569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570
Michael Wrightfb04fd52022-11-24 22:31:11 +00005571 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 synthesizeCancelationEventsForAllConnectionsLocked(options);
5573
5574 resetKeyRepeatLocked();
5575 releasePendingEventLocked();
5576 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005577 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005579 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005580 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005581 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582}
5583
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005584void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005585 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 dumpDispatchStateLocked(dump);
5587
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005588 std::istringstream stream(dump);
5589 std::string line;
5590
5591 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005592 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593 }
5594}
5595
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005596std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005597 std::string dump;
5598
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005599 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5600 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005601
5602 std::string windowName = "None";
5603 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005604 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005605 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5606 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5607 : "token has capture without window";
5608 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005609 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005610
5611 return dump;
5612}
5613
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005614void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005615 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5616 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5617 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005618 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619
Tiger Huang721e26f2018-07-24 22:26:19 +08005620 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5621 dump += StringPrintf(INDENT "FocusedApplications:\n");
5622 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5623 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005624 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005625 const std::chrono::duration timeout =
5626 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005627 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005628 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005629 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005632 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005634
Vishnu Nairc519ff72021-01-21 08:23:08 -08005635 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005636 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005638 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005639 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005640 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005641 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5642 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 }
5644 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005645 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646 }
5647
arthurhung6d4bed92021-03-17 11:59:33 +08005648 if (mDragState) {
5649 dump += StringPrintf(INDENT "DragState:\n");
5650 mDragState->dump(dump, INDENT2);
5651 }
5652
Arthur Hungb92218b2018-08-14 12:00:21 +08005653 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005654 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5655 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5656 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5657 const auto& displayInfo = it->second;
5658 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5659 displayInfo.logicalHeight);
5660 displayInfo.transform.dump(dump, "transform", INDENT4);
5661 } else {
5662 dump += INDENT2 "No DisplayInfo found!\n";
5663 }
5664
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005665 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005666 dump += INDENT2 "Windows:\n";
5667 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005668 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5669 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005671 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005672 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005673 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005674 "applicationInfo.name=%s, "
5675 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005676 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005677 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005678 windowInfo->displayId,
5679 windowInfo->inputConfig.string().c_str(),
5680 windowInfo->alpha, windowInfo->frameLeft,
5681 windowInfo->frameTop, windowInfo->frameRight,
5682 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005683 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005684 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005685 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005686 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005687 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005688 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005689 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005690 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005691 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005692 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005693 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005694 }
5695 } else {
5696 dump += INDENT2 "Windows: <none>\n";
5697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 }
5699 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005700 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 }
5702
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005703 if (!mGlobalMonitorsByDisplay.empty()) {
5704 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5705 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005706 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005709 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 }
5711
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005712 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713
5714 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005715 if (!mRecentQueue.empty()) {
5716 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005717 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005718 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005719 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005720 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 }
5722 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005723 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724 }
5725
5726 // Dump event currently being dispatched.
5727 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005728 dump += INDENT "PendingEvent:\n";
5729 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005730 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005731 dump += StringPrintf(", age=%" PRId64 "ms\n",
5732 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005734 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 }
5736
5737 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005738 if (!mInboundQueue.empty()) {
5739 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005740 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005741 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005742 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005743 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 }
5745 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005746 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747 }
5748
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005749 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005751 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005752 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005753 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005754 }
5755 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005756 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005757 }
5758
Prabir Pradhancef936d2021-07-21 16:17:52 +00005759 if (!mCommandQueue.empty()) {
5760 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5761 } else {
5762 dump += INDENT "CommandQueue: <empty>\n";
5763 }
5764
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005765 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005766 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005767 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005768 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005769 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005770 connection->inputChannel->getFd().get(),
5771 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005772 connection->getWindowName().c_str(),
5773 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005774 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005776 if (!connection->outboundQueue.empty()) {
5777 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5778 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005779 dump += dumpQueue(connection->outboundQueue, currentTime);
5780
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005782 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005785 if (!connection->waitQueue.empty()) {
5786 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5787 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005788 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005790 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
5792 }
5793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005794 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
5797 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005798 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5799 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005801 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802 }
5803
Antonio Kantek15beb512022-06-13 22:35:41 +00005804 if (!mTouchModePerDisplay.empty()) {
5805 dump += INDENT "TouchModePerDisplay:\n";
5806 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5807 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5808 std::to_string(touchMode).c_str());
5809 }
5810 } else {
5811 dump += INDENT "TouchModePerDisplay: <none>\n";
5812 }
5813
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005814 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005815 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5816 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5817 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005818 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005819 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820}
5821
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005822void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005823 const size_t numMonitors = monitors.size();
5824 for (size_t i = 0; i < numMonitors; i++) {
5825 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005826 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005827 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5828 dump += "\n";
5829 }
5830}
5831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005832class LooperEventCallback : public LooperCallback {
5833public:
5834 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5835 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5836
5837private:
5838 std::function<int(int events)> mCallback;
5839};
5840
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005841Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005842 if (DEBUG_CHANNEL_CREATION) {
5843 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005846 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005847 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005849
5850 if (result) {
5851 return base::Error(result) << "Failed to open input channel pair with name " << name;
5852 }
5853
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005855 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005856 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005857 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005858 std::shared_ptr<Connection> connection =
5859 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5860 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005862 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5863 ALOGE("Created a new connection, but the token %p is already known", token.get());
5864 }
5865 mConnectionsByToken.emplace(token, connection);
5866
5867 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5868 this, std::placeholders::_1, token);
5869
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005870 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5871 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 } // release lock
5873
5874 // Wake the looper because some connections have changed.
5875 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005876 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877}
5878
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005879Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005880 const std::string& name,
5881 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005882 std::shared_ptr<InputChannel> serverChannel;
5883 std::unique_ptr<InputChannel> clientChannel;
5884 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5885 if (result) {
5886 return base::Error(result) << "Failed to open input channel pair with name " << name;
5887 }
5888
Michael Wright3dd60e22019-03-27 22:06:44 +00005889 { // acquire lock
5890 std::scoped_lock _l(mLock);
5891
5892 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005893 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5894 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005895 }
5896
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005897 std::shared_ptr<Connection> connection =
5898 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005899 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005900 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005901
5902 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5903 ALOGE("Created a new connection, but the token %p is already known", token.get());
5904 }
5905 mConnectionsByToken.emplace(token, connection);
5906 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5907 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005908
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005909 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005910
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005911 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5912 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005913 }
Garfield Tan15601662020-09-22 15:32:38 -07005914
Michael Wright3dd60e22019-03-27 22:06:44 +00005915 // Wake the looper because some connections have changed.
5916 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005917 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005918}
5919
Garfield Tan15601662020-09-22 15:32:38 -07005920status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005922 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923
Harry Cutts33476232023-01-30 19:57:29 +00005924 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 if (status) {
5926 return status;
5927 }
5928 } // release lock
5929
5930 // Wake the poll loop because removing the connection may have changed the current
5931 // synchronization state.
5932 mLooper->wake();
5933 return OK;
5934}
5935
Garfield Tan15601662020-09-22 15:32:38 -07005936status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5937 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005938 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005939 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005940 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 return BAD_VALUE;
5942 }
5943
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005944 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005945
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005947 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 }
5949
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005950 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951
5952 nsecs_t currentTime = now();
5953 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5954
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005955 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 return OK;
5957}
5958
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005959void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005960 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5961 auto& [displayId, monitors] = *it;
5962 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5963 return monitor.inputChannel->getConnectionToken() == connectionToken;
5964 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005965
Michael Wright3dd60e22019-03-27 22:06:44 +00005966 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005968 } else {
5969 ++it;
5970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 }
5972}
5973
Michael Wright3dd60e22019-03-27 22:06:44 +00005974status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005975 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005976 return pilferPointersLocked(token);
5977}
Michael Wright3dd60e22019-03-27 22:06:44 +00005978
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005979status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005980 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5981 if (!requestingChannel) {
5982 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5983 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005984 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005986 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005987 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005988 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5989 " Ignoring.");
5990 return BAD_VALUE;
5991 }
5992
5993 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005994 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005995 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005996 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005997 "input channel stole pointer stream");
5998 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005999 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006000 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006001 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006002 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006003 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006004 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006005 if (channel != nullptr && channel->getConnectionToken() != token) {
6006 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6007 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6008 canceledWindows += channel->getName();
6009 }
6010 }
6011 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6012 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6013 canceledWindows.c_str());
6014
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006015 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006016 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006017 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006018
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07006019 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006020 return OK;
6021}
6022
Prabir Pradhan99987712020-11-10 18:43:05 -08006023void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6024 { // acquire lock
6025 std::scoped_lock _l(mLock);
6026 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006027 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006028 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6029 windowHandle != nullptr ? windowHandle->getName().c_str()
6030 : "token without window");
6031 }
6032
Vishnu Nairc519ff72021-01-21 08:23:08 -08006033 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006034 if (focusedToken != windowToken) {
6035 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6036 enabled ? "enable" : "disable");
6037 return;
6038 }
6039
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006040 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006041 ALOGW("Ignoring request to %s Pointer Capture: "
6042 "window has %s requested pointer capture.",
6043 enabled ? "enable" : "disable", enabled ? "already" : "not");
6044 return;
6045 }
6046
Christine Franksb768bb42021-11-29 12:11:31 -08006047 if (enabled) {
6048 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6049 mIneligibleDisplaysForPointerCapture.end(),
6050 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6051 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6052 return;
6053 }
6054 }
6055
Prabir Pradhan99987712020-11-10 18:43:05 -08006056 setPointerCaptureLocked(enabled);
6057 } // release lock
6058
6059 // Wake the thread to process command entries.
6060 mLooper->wake();
6061}
6062
Christine Franksb768bb42021-11-29 12:11:31 -08006063void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6064 { // acquire lock
6065 std::scoped_lock _l(mLock);
6066 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6067 if (!isEligible) {
6068 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6069 }
6070 } // release lock
6071}
6072
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006073std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
6074 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006075 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006076 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006077 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006078 }
6079 }
6080 }
6081 return std::nullopt;
6082}
6083
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006084std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6085 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006086 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006087 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006088 }
6089
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006090 for (const auto& [token, connection] : mConnectionsByToken) {
6091 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006092 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 }
6094 }
Robert Carr4e670e52018-08-15 13:26:12 -07006095
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006096 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097}
6098
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006099std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006100 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006101 if (connection == nullptr) {
6102 return "<nullptr>";
6103 }
6104 return connection->getInputChannelName();
6105}
6106
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006107void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006108 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006109 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006110}
6111
Prabir Pradhancef936d2021-07-21 16:17:52 +00006112void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006113 const std::shared_ptr<Connection>& connection,
6114 uint32_t seq, bool handled,
6115 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006116 // Handle post-event policy actions.
6117 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6118 if (dispatchEntryIt == connection->waitQueue.end()) {
6119 return;
6120 }
6121 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6122 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6123 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6124 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6125 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6126 }
6127 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6128 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6129 connection->inputChannel->getConnectionToken(),
6130 dispatchEntry->deliveryTime, consumeTime, finishTime);
6131 }
6132
6133 bool restartEvent;
6134 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6135 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6136 restartEvent =
6137 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6138 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6139 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6140 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6141 handled);
6142 } else {
6143 restartEvent = false;
6144 }
6145
6146 // Dequeue the event and start the next cycle.
6147 // Because the lock might have been released, it is possible that the
6148 // contents of the wait queue to have been drained, so we need to double-check
6149 // a few things.
6150 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6151 if (dispatchEntryIt != connection->waitQueue.end()) {
6152 dispatchEntry = *dispatchEntryIt;
6153 connection->waitQueue.erase(dispatchEntryIt);
6154 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6155 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6156 if (!connection->responsive) {
6157 connection->responsive = isConnectionResponsive(*connection);
6158 if (connection->responsive) {
6159 // The connection was unresponsive, and now it's responsive.
6160 processConnectionResponsiveLocked(*connection);
6161 }
6162 }
6163 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006164 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006165 connection->outboundQueue.push_front(dispatchEntry);
6166 traceOutboundQueueLength(*connection);
6167 } else {
6168 releaseDispatchEntry(dispatchEntry);
6169 }
6170 }
6171
6172 // Start the next dispatch cycle for this connection.
6173 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006174}
6175
Prabir Pradhancef936d2021-07-21 16:17:52 +00006176void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6177 const sp<IBinder>& newToken) {
6178 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6179 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006180 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006181 };
6182 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183}
6184
Prabir Pradhancef936d2021-07-21 16:17:52 +00006185void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6186 auto command = [this, token, x, y]() REQUIRES(mLock) {
6187 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006188 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006189 };
6190 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006191}
6192
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006193void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006194 if (connection == nullptr) {
6195 LOG_ALWAYS_FATAL("Caller must check for nullness");
6196 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006197 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6198 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006199 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006200 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006201 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006202 return;
6203 }
6204 /**
6205 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6206 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6207 * has changed. This could cause newer entries to time out before the already dispatched
6208 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6209 * processes the events linearly. So providing information about the oldest entry seems to be
6210 * most useful.
6211 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006212 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006213 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6214 std::string reason =
6215 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006216 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006217 ns2ms(currentWait),
6218 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006219 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006220 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006221
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006222 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6223
6224 // Stop waking up for events on this connection, it is already unresponsive
6225 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006226}
6227
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006228void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6229 std::string reason =
6230 StringPrintf("%s does not have a focused window", application->getName().c_str());
6231 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006232
Prabir Pradhancef936d2021-07-21 16:17:52 +00006233 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6234 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006235 mPolicy.notifyNoFocusedWindowAnr(application);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006236 };
6237 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006238}
6239
chaviw98318de2021-05-19 16:45:23 -05006240void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006241 const std::string& reason) {
6242 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6243 updateLastAnrStateLocked(windowLabel, reason);
6244}
6245
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006246void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6247 const std::string& reason) {
6248 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006249 updateLastAnrStateLocked(windowLabel, reason);
6250}
6251
6252void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6253 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006255 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 struct tm tm;
6257 localtime_r(&t, &tm);
6258 char timestr[64];
6259 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006260 mLastAnrState.clear();
6261 mLastAnrState += INDENT "ANR:\n";
6262 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006263 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6264 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006265 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006266}
6267
Prabir Pradhancef936d2021-07-21 16:17:52 +00006268void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6269 KeyEntry& entry) {
6270 const KeyEvent event = createKeyEvent(entry);
6271 nsecs_t delay = 0;
6272 { // release lock
6273 scoped_unlock unlock(mLock);
6274 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006275 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006276 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6277 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6278 std::to_string(t.duration().count()).c_str());
6279 }
6280 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006281
6282 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006283 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006285 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006286 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006287 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006288 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290}
6291
Prabir Pradhancef936d2021-07-21 16:17:52 +00006292void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006293 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006294 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006295 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006296 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006297 mPolicy.notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298 };
6299 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006300}
6301
Prabir Pradhanedd96402022-02-15 01:46:16 -08006302void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6303 std::optional<int32_t> pid) {
6304 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006306 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 };
6308 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006309}
6310
6311/**
6312 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6313 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6314 * command entry to the command queue.
6315 */
6316void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6317 std::string reason) {
6318 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006319 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006320 if (connection.monitor) {
6321 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6322 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006323 pid = findMonitorPidByTokenLocked(connectionToken);
6324 } else {
6325 // The connection is a window
6326 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6327 reason.c_str());
6328 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6329 if (handle != nullptr) {
6330 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006331 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006332 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006333 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006334}
6335
6336/**
6337 * Tell the policy that a connection has become responsive so that it can stop ANR.
6338 */
6339void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6340 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006341 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006342 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006343 pid = findMonitorPidByTokenLocked(connectionToken);
6344 } else {
6345 // The connection is a window
6346 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6347 if (handle != nullptr) {
6348 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006349 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006350 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006351 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006352}
6353
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006354bool InputDispatcher::afterKeyEventLockedInterruptable(
6355 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6356 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006357 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006358 if (!handled) {
6359 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006360 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006361 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006362 return false;
6363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006365 // Get the fallback key state.
6366 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006367 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006368 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006369 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006370 connection->inputState.removeFallbackKey(originalKeyCode);
6371 }
6372
6373 if (handled || !dispatchEntry->hasForegroundTarget()) {
6374 // If the application handles the original key for which we previously
6375 // generated a fallback or if the window is not a foreground window,
6376 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006377 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006378 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006379 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6380 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6381 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6382 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6383 keyEntry.policyFlags);
6384 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006385 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006386 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387
6388 mLock.unlock();
6389
Prabir Pradhana41d2442023-04-20 21:30:40 +00006390 if (const auto unhandledKeyFallback =
6391 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6392 event, keyEntry.policyFlags);
6393 unhandledKeyFallback) {
6394 event = *unhandledKeyFallback;
6395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396
6397 mLock.lock();
6398
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006399 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006400 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006401 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006402 "application handled the original non-fallback key "
6403 "or is no longer a foreground target, "
6404 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006405 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 connection->inputState.removeFallbackKey(originalKeyCode);
6409 }
6410 } else {
6411 // If the application did not handle a non-fallback key, first check
6412 // that we are in a good state to perform unhandled key event processing
6413 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006414 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006415 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006416 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6417 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6418 "since this is not an initial down. "
6419 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6420 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6421 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006422 return false;
6423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006426 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6427 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6428 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6429 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6430 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006431 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432
6433 mLock.unlock();
6434
Prabir Pradhana41d2442023-04-20 21:30:40 +00006435 bool fallback = false;
6436 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6437 event, keyEntry.policyFlags);
6438 fb) {
6439 fallback = true;
6440 event = *fb;
6441 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442
6443 mLock.lock();
6444
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006445 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006446 connection->inputState.removeFallbackKey(originalKeyCode);
6447 return false;
6448 }
6449
6450 // Latch the fallback keycode for this key on an initial down.
6451 // The fallback keycode cannot change at any other point in the lifecycle.
6452 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006458 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006459 }
6460
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462
6463 // Cancel the fallback key if the policy decides not to send it anymore.
6464 // We will continue to dispatch the key to the policy but we will no
6465 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006466 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6467 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006468 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6469 if (fallback) {
6470 ALOGD("Unhandled key event: Policy requested to send key %d"
6471 "as a fallback for %d, but on the DOWN it had requested "
6472 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 } else {
6475 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6476 "but on the DOWN it had requested to send %d. "
6477 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006478 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006479 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006481
Michael Wrightfb04fd52022-11-24 22:31:11 +00006482 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006484 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 synthesizeCancelationEventsForConnectionLocked(connection, options);
6486
6487 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006488 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006489 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006490 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491 }
6492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006494 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6495 {
6496 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006498 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006499 for (const auto& [key, value] : fallbackKeys) {
6500 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006501 }
6502 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6503 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006505 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006506
6507 if (fallback) {
6508 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006509 keyEntry.eventTime = event.getEventTime();
6510 keyEntry.deviceId = event.getDeviceId();
6511 keyEntry.source = event.getSource();
6512 keyEntry.displayId = event.getDisplayId();
6513 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006514 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006515 keyEntry.scanCode = event.getScanCode();
6516 keyEntry.metaState = event.getMetaState();
6517 keyEntry.repeatCount = event.getRepeatCount();
6518 keyEntry.downTime = event.getDownTime();
6519 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006520
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006521 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6522 ALOGD("Unhandled key event: Dispatching fallback key. "
6523 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006524 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006525 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006526 return true; // restart the event
6527 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006528 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6529 ALOGD("Unhandled key event: No fallback key.");
6530 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006531
6532 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006533 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534 }
6535 }
6536 return false;
6537}
6538
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006539bool InputDispatcher::afterMotionEventLockedInterruptable(
6540 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6541 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542 return false;
6543}
6544
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545void InputDispatcher::traceInboundQueueLengthLocked() {
6546 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006547 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 }
6549}
6550
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006551void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 if (ATRACE_ENABLED()) {
6553 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006554 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6555 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556 }
6557}
6558
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006559void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560 if (ATRACE_ENABLED()) {
6561 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006562 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6563 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 }
6565}
6566
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006567void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006568 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006570 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006571 dumpDispatchStateLocked(dump);
6572
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006573 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006574 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006575 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006576 }
6577}
6578
6579void InputDispatcher::monitor() {
6580 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006581 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006583 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584}
6585
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006586/**
6587 * Wake up the dispatcher and wait until it processes all events and commands.
6588 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6589 * this method can be safely called from any thread, as long as you've ensured that
6590 * the work you are interested in completing has already been queued.
6591 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006592bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006593 /**
6594 * Timeout should represent the longest possible time that a device might spend processing
6595 * events and commands.
6596 */
6597 constexpr std::chrono::duration TIMEOUT = 100ms;
6598 std::unique_lock lock(mLock);
6599 mLooper->wake();
6600 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6601 return result == std::cv_status::no_timeout;
6602}
6603
Vishnu Naire798b472020-07-23 13:52:21 -07006604/**
6605 * Sets focus to the window identified by the token. This must be called
6606 * after updating any input window handles.
6607 *
6608 * Params:
6609 * request.token - input channel token used to identify the window that should gain focus.
6610 * request.focusedToken - the token that the caller expects currently to be focused. If the
6611 * specified token does not match the currently focused window, this request will be dropped.
6612 * If the specified focused token matches the currently focused window, the call will succeed.
6613 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6614 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6615 * when requesting the focus change. This determines which request gets
6616 * precedence if there is a focus change request from another source such as pointer down.
6617 */
Vishnu Nair958da932020-08-21 17:12:37 -07006618void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6619 { // acquire lock
6620 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006621 std::optional<FocusResolver::FocusChanges> changes =
6622 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6623 if (changes) {
6624 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006625 }
6626 } // release lock
6627 // Wake up poll loop since it may need to make new input dispatching choices.
6628 mLooper->wake();
6629}
6630
Vishnu Nairc519ff72021-01-21 08:23:08 -08006631void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6632 if (changes.oldFocus) {
6633 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006634 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006635 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006636 "focus left window");
6637 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006638 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006639 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006640 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006641 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006642 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006643 }
6644
Prabir Pradhan99987712020-11-10 18:43:05 -08006645 // If a window has pointer capture, then it must have focus. We need to ensure that this
6646 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6647 // If the window loses focus before it loses pointer capture, then the window can be in a state
6648 // where it has pointer capture but not focus, violating the contract. Therefore we must
6649 // dispatch the pointer capture event before the focus event. Since focus events are added to
6650 // the front of the queue (above), we add the pointer capture event to the front of the queue
6651 // after the focus events are added. This ensures the pointer capture event ends up at the
6652 // front.
6653 disablePointerCaptureForcedLocked();
6654
Vishnu Nairc519ff72021-01-21 08:23:08 -08006655 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006656 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006657 }
6658}
Vishnu Nair958da932020-08-21 17:12:37 -07006659
Prabir Pradhan99987712020-11-10 18:43:05 -08006660void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006661 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006662 return;
6663 }
6664
6665 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6666
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006667 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006668 setPointerCaptureLocked(false);
6669 }
6670
6671 if (!mWindowTokenWithPointerCapture) {
6672 // No need to send capture changes because no window has capture.
6673 return;
6674 }
6675
6676 if (mPendingEvent != nullptr) {
6677 // Move the pending event to the front of the queue. This will give the chance
6678 // for the pending event to be dropped if it is a captured event.
6679 mInboundQueue.push_front(mPendingEvent);
6680 mPendingEvent = nullptr;
6681 }
6682
6683 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006684 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006685 mInboundQueue.push_front(std::move(entry));
6686}
6687
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006688void InputDispatcher::setPointerCaptureLocked(bool enable) {
6689 mCurrentPointerCaptureRequest.enable = enable;
6690 mCurrentPointerCaptureRequest.seq++;
6691 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006692 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006693 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006694 };
6695 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006696}
6697
Vishnu Nair599f1412021-06-21 10:39:58 -07006698void InputDispatcher::displayRemoved(int32_t displayId) {
6699 { // acquire lock
6700 std::scoped_lock _l(mLock);
6701 // Set an empty list to remove all handles from the specific display.
6702 setInputWindowsLocked(/* window handles */ {}, displayId);
6703 setFocusedApplicationLocked(displayId, nullptr);
6704 // Call focus resolver to clean up stale requests. This must be called after input windows
6705 // have been removed for the removed display.
6706 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006707 // Reset pointer capture eligibility, regardless of previous state.
6708 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006709 // Remove the associated touch mode state.
6710 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006711 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006712 } // release lock
6713
6714 // Wake up poll loop since it may need to make new input dispatching choices.
6715 mLooper->wake();
6716}
6717
Patrick Williamsd828f302023-04-28 17:52:08 -05006718void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006719 // The listener sends the windows as a flattened array. Separate the windows by display for
6720 // more convenient parsing.
6721 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006722 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006723 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006724 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006725 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006726
6727 { // acquire lock
6728 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006729
6730 // Ensure that we have an entry created for all existing displays so that if a displayId has
6731 // no windows, we can tell that the windows were removed from the display.
6732 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6733 handlesPerDisplay[displayId];
6734 }
6735
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006736 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006737 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006738 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6739 }
6740
6741 for (const auto& [displayId, handles] : handlesPerDisplay) {
6742 setInputWindowsLocked(handles, displayId);
6743 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006744
6745 if (update.vsyncId < mWindowInfosVsyncId) {
6746 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6747 ", current update vsync id: %" PRId64,
6748 mWindowInfosVsyncId, update.vsyncId);
6749 }
6750 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006751 }
6752 // Wake up poll loop since it may need to make new input dispatching choices.
6753 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006754}
6755
Vishnu Nair062a8672021-09-03 16:07:44 -07006756bool InputDispatcher::shouldDropInput(
6757 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006758 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6759 (windowHandle->getInfo()->inputConfig.test(
6760 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006761 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006762 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6763 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006764 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006765 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006766 windowHandle->getInfo()->displayId);
6767 return true;
6768 }
6769 return false;
6770}
6771
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006772void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006773 const gui::WindowInfosUpdate& update) {
6774 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006775}
6776
Arthur Hungdfd528e2021-12-08 13:23:04 +00006777void InputDispatcher::cancelCurrentTouch() {
6778 {
6779 std::scoped_lock _l(mLock);
6780 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006781 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006782 "cancel current touch");
6783 synthesizeCancelationEventsForAllConnectionsLocked(options);
6784
6785 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006786 }
6787 // Wake up poll loop since there might be work to do.
6788 mLooper->wake();
6789}
6790
Prabir Pradhan87112a72023-04-20 19:13:39 +00006791void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006792 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006793
6794 std::scoped_lock _l(mLock);
6795 mConfig = config;
6796}
6797
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006798void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6799 std::scoped_lock _l(mLock);
6800 mMonitorDispatchingTimeout = timeout;
6801}
6802
Arthur Hungc539dbb2022-12-08 07:45:36 +00006803void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6804 const sp<WindowInfoHandle>& oldWindowHandle,
6805 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006806 TouchState& state, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006807 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006808 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6809 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006810 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6811 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6812 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6813 newWindowHandle->getInfo()->inputConfig.test(
6814 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6815 const sp<WindowInfoHandle> oldWallpaper =
6816 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6817 const sp<WindowInfoHandle> newWallpaper =
6818 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6819 if (oldWallpaper == newWallpaper) {
6820 return;
6821 }
6822
6823 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006824 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6825 addWindowTargetLocked(oldWallpaper,
6826 oldTouchedWindow.targetFlags |
6827 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6828 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6829 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006830 }
6831
6832 if (newWallpaper != nullptr) {
6833 state.addOrUpdateWindow(newWallpaper,
6834 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6835 InputTarget::Flags::WINDOW_IS_OBSCURED |
6836 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6837 pointerIds);
6838 }
6839}
6840
6841void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6842 ftl::Flags<InputTarget::Flags> newTargetFlags,
6843 const sp<WindowInfoHandle> fromWindowHandle,
6844 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006845 TouchState& state,
6846 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006847 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6848 fromWindowHandle->getInfo()->inputConfig.test(
6849 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6850 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6851 toWindowHandle->getInfo()->inputConfig.test(
6852 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6853
6854 const sp<WindowInfoHandle> oldWallpaper =
6855 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6856 const sp<WindowInfoHandle> newWallpaper =
6857 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6858 if (oldWallpaper == newWallpaper) {
6859 return;
6860 }
6861
6862 if (oldWallpaper != nullptr) {
6863 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6864 "transferring touch focus to another window");
6865 state.removeWindowByToken(oldWallpaper->getToken());
6866 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6867 }
6868
6869 if (newWallpaper != nullptr) {
6870 nsecs_t downTimeInTarget = now();
6871 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6872 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6873 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6874 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6875 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006876 std::shared_ptr<Connection> wallpaperConnection =
6877 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006878 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006879 std::shared_ptr<Connection> toConnection =
6880 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006881 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6882 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6883 wallpaperFlags);
6884 }
6885 }
6886}
6887
6888sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6889 const sp<WindowInfoHandle>& windowHandle) const {
6890 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6891 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6892 bool foundWindow = false;
6893 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6894 if (!foundWindow && otherHandle != windowHandle) {
6895 continue;
6896 }
6897 if (windowHandle == otherHandle) {
6898 foundWindow = true;
6899 continue;
6900 }
6901
6902 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6903 return otherHandle;
6904 }
6905 }
6906 return nullptr;
6907}
6908
Garfield Tane84e6f92019-08-29 17:28:41 -07006909} // namespace android::inputdispatcher