blob: 6033398b25a550d06b3b6ea665c124b67689a046 [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>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056#define INDENT " "
57#define INDENT2 " "
58#define INDENT3 " "
59#define INDENT4 " "
60
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080061using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070062using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080063using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000064using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070066using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050067using android::gui::FocusRequest;
68using android::gui::TouchOcclusionMode;
69using android::gui::WindowInfo;
70using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080071using android::os::InputEventInjectionResult;
72using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000073namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080074
Siarhei Vishniakou17f12282023-11-02 13:40:29 -070075static const bool REMOVE_APP_SWITCH_DROPS = input_flags::remove_app_switch_drops();
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Prabir Pradhancef936d2021-07-21 16:17:52 +000079namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000080// Temporarily releases a held mutex for the lifetime of the instance.
81// Named to match std::scoped_lock
82class scoped_unlock {
83public:
84 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
85 ~scoped_unlock() { mMutex.lock(); }
86
87private:
88 std::mutex& mMutex;
89};
90
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// Default input dispatching timeout if there is no focused application or paused window
92// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080093const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
94 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
95 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Amount of time to allow for all pending events to be processed when an app switch
98// key is on the way. This is used to preempt input dispatch and drop input events
99// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000100constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800102const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// 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 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Antonio Kantekea47acb2021-12-23 12:41:25 -0800118// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000121constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000122
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000123const ui::Transform kIdentityTransform;
124
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000125inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126 return systemTime(SYSTEM_TIME_MONOTONIC);
127}
128
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700129inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000130 if (binder == nullptr) {
131 return "<null>";
132 }
133 return StringPrintf("%p", binder.get());
134}
135
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000136static std::string uidString(const gui::Uid& uid) {
137 return uid.toString();
138}
139
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700140Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 case AKEY_EVENT_ACTION_DOWN:
143 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 }
148}
149
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700150Result<void> validateKeyEvent(int32_t action) {
151 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152}
153
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700157 case AMOTION_EVENT_ACTION_UP: {
158 if (pointerCount != 1) {
159 return Error() << "invalid pointer count " << pointerCount;
160 }
161 return {};
162 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 case AMOTION_EVENT_ACTION_HOVER_ENTER:
165 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700166 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
167 if (pointerCount < 1) {
168 return Error() << "invalid pointer count " << pointerCount;
169 }
170 return {};
171 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800172 case AMOTION_EVENT_ACTION_CANCEL:
173 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700175 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_POINTER_DOWN:
177 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800178 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179 if (index < 0) {
180 return Error() << "invalid index " << index << " for "
181 << MotionEvent::actionToString(action);
182 }
183 if (index >= pointerCount) {
184 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
185 }
186 if (pointerCount <= 1) {
187 return Error() << "invalid pointer count " << pointerCount << " for "
188 << MotionEvent::actionToString(action);
189 }
190 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700191 }
192 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
194 if (actionButton == 0) {
195 return Error() << "action button should be nonzero for "
196 << MotionEvent::actionToString(action);
197 }
198 return {};
199 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700201 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
203}
204
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000205int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500206 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
207}
208
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700209Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
210 const PointerProperties* pointerProperties) {
211 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
212 if (!actionCheck.ok()) {
213 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
215 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700216 return Error() << "Motion event has invalid pointer count " << pointerCount
217 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800219 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 for (size_t i = 0; i < pointerCount; i++) {
221 int32_t id = pointerProperties[i].id;
222 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700223 return Error() << "Motion event has invalid pointer id " << id
224 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800226 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700227 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800229 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700231 return {};
232}
233
234Result<void> validateInputEvent(const InputEvent& event) {
235 switch (event.getType()) {
236 case InputEventType::KEY: {
237 const KeyEvent& key = static_cast<const KeyEvent&>(event);
238 const int32_t action = key.getAction();
239 return validateKeyEvent(action);
240 }
241 case InputEventType::MOTION: {
242 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
243 const int32_t action = motion.getAction();
244 const size_t pointerCount = motion.getPointerCount();
245 const PointerProperties* pointerProperties = motion.getPointerProperties();
246 const int32_t actionButton = motion.getActionButton();
247 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
248 }
249 default: {
250 return {};
251 }
252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253}
254
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000255std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000257 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 }
259
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000260 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 bool first = true;
262 Region::const_iterator cur = region.begin();
263 Region::const_iterator const tail = region.end();
264 while (cur != tail) {
265 if (first) {
266 first = false;
267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 cur++;
272 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000273 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274}
275
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000276std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
277 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500278 constexpr size_t maxEntries = 50; // max events to print
279 constexpr size_t skipBegin = maxEntries / 2;
280 const size_t skipEnd = queue.size() - maxEntries / 2;
281 // skip from maxEntries / 2 ... size() - maxEntries/2
282 // only print from 0 .. skipBegin and then from skipEnd .. size()
283
284 std::string dump;
285 for (size_t i = 0; i < queue.size(); i++) {
286 const DispatchEntry& entry = *queue[i];
287 if (i >= skipBegin && i < skipEnd) {
288 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
289 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
290 continue;
291 }
292 dump.append(INDENT4);
293 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000294 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
295 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500296 ns2ms(currentTime - entry.eventEntry->eventTime));
297 if (entry.deliveryTime != 0) {
298 // This entry was delivered, so add information on how long we've been waiting
299 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
300 }
301 dump.append("\n");
302 }
303 return dump;
304}
305
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700306/**
307 * Find the entry in std::unordered_map by key, and return it.
308 * If the entry is not found, return a default constructed entry.
309 *
310 * Useful when the entries are vectors, since an empty vector will be returned
311 * if the entry is not found.
312 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
313 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700314template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000315V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700316 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700317 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800318}
319
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000320bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700321 if (first == second) {
322 return true;
323 }
324
325 if (first == nullptr || second == nullptr) {
326 return false;
327 }
328
329 return first->getToken() == second->getToken();
330}
331
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000332bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000333 if (first == nullptr || second == nullptr) {
334 return false;
335 }
336 return first->applicationInfo.token != nullptr &&
337 first->applicationInfo.token == second->applicationInfo.token;
338}
339
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800340template <typename T>
341size_t firstMarkedBit(T set) {
342 // TODO: replace with std::countr_zero from <bit> when that's available
343 LOG_ALWAYS_FATAL_IF(set.none());
344 size_t i = 0;
345 while (!set.test(i)) {
346 i++;
347 }
348 return i;
349}
350
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800351std::unique_ptr<DispatchEntry> createDispatchEntry(
Prabir Pradhan24047542023-11-02 17:14:59 +0000352 const InputTarget& inputTarget, std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800353 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700354 if (inputTarget.useDefaultPointerTransform()) {
355 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700356 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700357 inputTarget.displayTransform,
358 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359 }
360
361 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
362 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
363
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700364 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700365 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 // Use the first pointer information to normalize all other pointers. This could be any pointer
368 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 // uses the transform for the normalized pointer.
370 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800371 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373
374 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700375 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
377 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700378 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379
380 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700381 // First, apply the current pointer's transform to update the coordinates into
382 // window space.
383 pointerCoords[pointerIndex].transform(currTransform);
384 // Next, apply the inverse transform of the normalized coordinates so the
385 // current coordinates are transformed into the normalized coordinate space.
386 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387 }
388
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700389 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000390 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
391 motionEntry.eventTime, motionEntry.deviceId,
392 motionEntry.source, motionEntry.displayId,
393 motionEntry.policyFlags, motionEntry.action,
394 motionEntry.actionButton, motionEntry.flags,
395 motionEntry.metaState, motionEntry.buttonState,
396 motionEntry.classification, motionEntry.edgeFlags,
397 motionEntry.xPrecision, motionEntry.yPrecision,
398 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
399 motionEntry.downTime, motionEntry.pointerProperties,
400 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000401
402 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700403 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700404 firstPointerTransform, inputTarget.displayTransform,
405 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000406 return dispatchEntry;
407}
408
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000409status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
410 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700411 std::unique_ptr<InputChannel> uniqueServerChannel;
412 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
413
414 serverChannel = std::move(uniqueServerChannel);
415 return result;
416}
417
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500418template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000419bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500420 if (lhs == nullptr && rhs == nullptr) {
421 return true;
422 }
423 if (lhs == nullptr || rhs == nullptr) {
424 return false;
425 }
426 return *lhs == *rhs;
427}
428
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000429KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000430 KeyEvent event;
431 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
432 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
433 entry.repeatCount, entry.downTime, entry.eventTime);
434 return event;
435}
436
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000437bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000438 // Do not keep track of gesture monitors. They receive every event and would disproportionately
439 // affect the statistics.
440 if (connection.monitor) {
441 return false;
442 }
443 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
444 if (!connection.responsive) {
445 return false;
446 }
447 return true;
448}
449
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000450bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000451 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
452 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000453 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
454 return false;
455 }
456 // Only track latency for events that originated from hardware
457 if (eventEntry.isSynthesized()) {
458 return false;
459 }
460 const EventEntry::Type& inputEventEntryType = eventEntry.type;
461 if (inputEventEntryType == EventEntry::Type::KEY) {
462 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
463 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
464 return false;
465 }
466 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
467 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
468 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
469 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
470 return false;
471 }
472 } else {
473 // Not a key or a motion
474 return false;
475 }
476 if (!shouldReportMetricsForConnection(connection)) {
477 return false;
478 }
479 return true;
480}
481
Prabir Pradhancef936d2021-07-21 16:17:52 +0000482/**
483 * Connection is responsive if it has no events in the waitQueue that are older than the
484 * current time.
485 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000486bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000487 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000488 for (const auto& dispatchEntry : connection.waitQueue) {
489 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000490 return false;
491 }
492 }
493 return true;
494}
495
Antonio Kantekf16f2832021-09-28 04:39:20 +0000496// Returns true if the event type passed as argument represents a user activity.
497bool isUserActivityEvent(const EventEntry& eventEntry) {
498 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000499 case EventEntry::Type::CONFIGURATION_CHANGED:
500 case EventEntry::Type::DEVICE_RESET:
501 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000502 case EventEntry::Type::FOCUS:
503 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000504 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000505 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000506 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507 case EventEntry::Type::KEY:
508 case EventEntry::Type::MOTION:
509 return true;
510 }
511}
512
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800513// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000514bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000515 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800516 const auto inputConfig = windowInfo.inputConfig;
517 if (windowInfo.displayId != displayId ||
518 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800519 return false;
520 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700521 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800522 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800523 return false;
524 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000525
526 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
527 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
528 // the window. Points on the right and bottom edges should not be inside the window, so we need
529 // to be careful about performing a hit test when the display is rotated, since the "right" and
530 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
531 // logical display in which WM determined the bounds. Perform the hit test in the logical
532 // display space to ensure these edges are considered correctly in all orientations.
533 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
534 const auto p = displayTransform.transform(x, y);
535 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800536 return false;
537 }
538 return true;
539}
540
Prabir Pradhand65552b2021-10-07 11:23:50 -0700541bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
542 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000543 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700544}
545
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800546// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000547// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
548// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
549// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800550// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000551bool canReceiveForegroundTouches(const WindowInfo& info) {
552 // A non-touchable window can still receive touch events (e.g. in the case of
553 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
554 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
555}
556
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000557bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700558 if (windowHandle == nullptr) {
559 return false;
560 }
561 const WindowInfo* windowInfo = windowHandle->getInfo();
562 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
563 return true;
564 }
565 return false;
566}
567
Prabir Pradhan5735a322022-04-11 17:23:34 +0000568// Checks targeted injection using the window's owner's uid.
569// Returns an empty string if an entry can be sent to the given window, or an error message if the
570// entry is a targeted injection whose uid target doesn't match the window owner.
571std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
572 const EventEntry& entry) {
573 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
574 // The event was not injected, or the injected event does not target a window.
575 return {};
576 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000577 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000578 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000579 return StringPrintf("No valid window target for injection into uid %s.",
580 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000581 }
582 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000583 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
584 "owned by uid %s.",
585 uid.toString().c_str(), window->getName().c_str(),
586 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000587 }
588 return {};
589}
590
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000591std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700592 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
593 // Always dispatch mouse events to cursor position.
594 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000595 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700596 }
597
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700598 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000599 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
600 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700601}
602
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700603std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
604 if (eventEntry.type == EventEntry::Type::KEY) {
605 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
606 return keyEntry.downTime;
607 } else if (eventEntry.type == EventEntry::Type::MOTION) {
608 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
609 return motionEntry.downTime;
610 }
611 return std::nullopt;
612}
613
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000614/**
615 * Compare the old touch state to the new touch state, and generate the corresponding touched
616 * windows (== input targets).
617 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
618 * If the pointer just entered the new window, produce HOVER_ENTER.
619 * For pointers remaining in the window, produce HOVER_MOVE.
620 */
621std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
622 const TouchState& newTouchState,
623 const MotionEntry& entry) {
624 std::vector<TouchedWindow> out;
625 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700626
627 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
628 // ACTION_SCROLL events should not affect the hovering pointer dispatch
629 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000630 }
631
632 // We should consider all hovering pointers here. But for now, just use the first one
633 const int32_t pointerId = entry.pointerProperties[0].id;
634
635 std::set<sp<WindowInfoHandle>> oldWindows;
636 if (oldState != nullptr) {
637 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
638 }
639
640 std::set<sp<WindowInfoHandle>> newWindows =
641 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
642
643 // If the pointer is no longer in the new window set, send HOVER_EXIT.
644 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
645 if (newWindows.find(oldWindow) == newWindows.end()) {
646 TouchedWindow touchedWindow;
647 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000648 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000649 out.push_back(touchedWindow);
650 }
651 }
652
653 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
654 TouchedWindow touchedWindow;
655 touchedWindow.windowHandle = newWindow;
656 if (oldWindows.find(newWindow) == oldWindows.end()) {
657 // Any windows that have this pointer now, and didn't have it before, should get
658 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000659 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 } else {
661 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700662 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700663 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000664 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
665 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700666 // The Accessibility injected touch exploration event stream
667 // has known inconsistencies, so log ERROR instead of
668 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700669 severity = android::base::LogSeverity::ERROR;
670 }
671 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700672 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000673 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000674 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700675 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000676 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
677 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
678 }
679 out.push_back(touchedWindow);
680 }
681 return out;
682}
683
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800684template <typename T>
685std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
686 left.insert(left.end(), right.begin(), right.end());
687 return left;
688}
689
Harry Cuttsb166c002023-05-09 13:06:05 +0000690// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
691// both.
692void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
693 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
694 if (!window.windowHandle->getInfo()->inputConfig.test(
695 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
696 // In addition to TouchState, erase this window from the input targets! We don't have a
697 // good way to do this today except by adding a nested loop.
698 // TODO(b/282025641): simplify this code once InputTargets are being identified
699 // separately from TouchedWindows.
700 std::erase_if(targets, [&](const InputTarget& target) {
701 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
702 });
703 return true;
704 }
705 return false;
706 });
707}
708
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700709/**
710 * In general, touch should be always split between windows. Some exceptions:
711 * 1. Don't split touch if all of the below is true:
712 * (a) we have an active pointer down *and*
713 * (b) a new pointer is going down that's from the same device *and*
714 * (c) the window that's receiving the current pointer does not support split touch.
715 * 2. Don't split mouse events
716 */
717bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
718 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
719 // We should never split mouse events
720 return false;
721 }
722 for (const TouchedWindow& touchedWindow : touchState.windows) {
723 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
724 // Spy windows should not affect whether or not touch is split.
725 continue;
726 }
727 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
728 continue;
729 }
730 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
731 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
732 // Wallpaper window should not affect whether or not touch is split
733 continue;
734 }
735
736 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
737 return false;
738 }
739 }
740 return true;
741}
742
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000743} // namespace
744
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745// --- InputDispatcher ---
746
Prabir Pradhana41d2442023-04-20 21:30:40 +0000747InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Garfield Tan00f511d2019-06-12 16:55:40 -0700748 : mPolicy(policy),
749 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700750 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800751 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700752 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700753 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700754 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800755 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700756 mDispatchEnabled(false),
757 mDispatchFrozen(false),
758 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100759 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000760 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800761 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000762 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000763 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700764 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800765 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700767 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700768#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700769 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700770#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700771 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772}
773
774InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000775 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776
Prabir Pradhancef936d2021-07-21 16:17:52 +0000777 resetKeyRepeatLocked();
778 releasePendingEventLocked();
779 drainInboundQueueLocked();
780 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000782 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700783 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000784 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 }
786}
787
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700788status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700789 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700790 return ALREADY_EXISTS;
791 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700792 mThread = std::make_unique<InputThread>(
793 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
794 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700795}
796
797status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700798 if (mThread && mThread->isCallingThread()) {
799 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700800 return INVALID_OPERATION;
801 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700802 mThread.reset();
803 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804}
805
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700807 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800809 std::scoped_lock _l(mLock);
810 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811
812 // Run a dispatch loop if there are no pending commands.
813 // The dispatch loop might enqueue commands to run afterwards.
814 if (!haveCommandsLocked()) {
815 dispatchOnceInnerLocked(&nextWakeupTime);
816 }
817
818 // Run all pending commands if there are any.
819 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000820 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700821 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800823
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700824 // If we are still waiting for ack on some events,
825 // we might have to wake up earlier to check if an app is anr'ing.
826 const nsecs_t nextAnrCheck = processAnrsLocked();
827 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
828
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800829 // We are about to enter an infinitely long sleep, because we have no commands or
830 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700831 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800832 mDispatcherEnteredIdle.notify_all();
833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 } // release lock
835
836 // Wait for callback or timeout or wake. (make sure we round up, not down)
837 nsecs_t currentTime = now();
838 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
839 mLooper->pollOnce(timeoutMillis);
840}
841
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700842/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500843 * Raise ANR if there is no focused window.
844 * Before the ANR is raised, do a final state check:
845 * 1. The currently focused application must be the same one we are waiting for.
846 * 2. Ensure we still don't have a focused window.
847 */
848void InputDispatcher::processNoFocusedWindowAnrLocked() {
849 // Check if the application that we are waiting for is still focused.
850 std::shared_ptr<InputApplicationHandle> focusedApplication =
851 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
852 if (focusedApplication == nullptr ||
853 focusedApplication->getApplicationToken() !=
854 mAwaitedFocusedApplication->getApplicationToken()) {
855 // Unexpected because we should have reset the ANR timer when focused application changed
856 ALOGE("Waited for a focused window, but focused application has already changed to %s",
857 focusedApplication->getName().c_str());
858 return; // The focused application has changed.
859 }
860
chaviw98318de2021-05-19 16:45:23 -0500861 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500862 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
863 if (focusedWindowHandle != nullptr) {
864 return; // We now have a focused window. No need for ANR.
865 }
866 onAnrLocked(mAwaitedFocusedApplication);
867}
868
869/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700870 * Check if any of the connections' wait queues have events that are too old.
871 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
872 * Return the time at which we should wake up next.
873 */
874nsecs_t InputDispatcher::processAnrsLocked() {
875 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700876 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
878 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
879 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500880 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700881 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500882 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700883 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700884 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500885 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
887 }
888 }
889
890 // Check if any connection ANRs are due
891 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
892 if (currentTime < nextAnrCheck) { // most likely scenario
893 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
894 }
895
896 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700897 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 if (connection == nullptr) {
899 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
900 return nextAnrCheck;
901 }
902 connection->responsive = false;
903 // Stop waking up for this unresponsive connection
904 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000905 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700906 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907}
908
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800909std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700910 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800911 if (connection->monitor) {
912 return mMonitorDispatchingTimeout;
913 }
914 const sp<WindowInfoHandle> window =
915 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700916 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500917 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700918 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500919 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700920}
921
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
923 nsecs_t currentTime = now();
924
Jeff Browndc5992e2014-04-11 01:27:26 -0700925 // Reset the key repeat timer whenever normal dispatch is suspended while the
926 // device is in a non-interactive state. This is to ensure that we abort a key
927 // repeat if the device is just coming out of sleep.
928 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 resetKeyRepeatLocked();
930 }
931
932 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
933 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100934 if (DEBUG_FOCUS) {
935 ALOGD("Dispatch frozen. Waiting some more.");
936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 return;
938 }
939
940 // Optimize latency of app switches.
941 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
942 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700943 bool isAppSwitchDue;
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700944 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700945 isAppSwitchDue = mAppSwitchDueTime <= currentTime;
946 if (mAppSwitchDueTime < *nextWakeupTime) {
947 *nextWakeupTime = mAppSwitchDueTime;
948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 }
950
951 // Ready to start a new event.
952 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700954 if (mInboundQueue.empty()) {
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700955 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700956 if (isAppSwitchDue) {
957 // The inbound queue is empty so the app switch key we were waiting
958 // for will never arrive. Stop waiting for it.
959 resetPendingAppSwitchLocked(false);
960 isAppSwitchDue = false;
961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 }
963
964 // Synthesize a key repeat if appropriate.
965 if (mKeyRepeatState.lastKeyEntry) {
966 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
967 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
968 } else {
969 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
970 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
971 }
972 }
973 }
974
975 // Nothing to do if there is no pending event.
976 if (!mPendingEvent) {
977 return;
978 }
979 } else {
980 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 mPendingEvent = mInboundQueue.front();
982 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 traceInboundQueueLengthLocked();
984 }
985
986 // Poke user activity for this event.
987 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700988 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
991
992 // Now we have an event to dispatch.
993 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700994 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700996 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700998 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001000 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001004 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 }
1006
1007 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001008 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001009 const ConfigurationChangedEntry& typedEntry =
1010 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001012 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 break;
1014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001016 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001017 const DeviceResetEntry& typedEntry =
1018 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001020 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 break;
1022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001024 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001025 std::shared_ptr<const FocusEntry> typedEntry =
1026 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001027 dispatchFocusLocked(currentTime, typedEntry);
1028 done = true;
1029 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1030 break;
1031 }
1032
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001033 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001034 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001035 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1036 done = true;
1037 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1038 break;
1039 }
1040
Prabir Pradhan99987712020-11-10 18:43:05 -08001041 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1042 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001043 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001044 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1045 done = true;
1046 break;
1047 }
1048
arthurhungb89ccb02020-12-30 16:19:01 +08001049 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001050 std::shared_ptr<const DragEntry> typedEntry =
1051 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001052 dispatchDragLocked(currentTime, typedEntry);
1053 done = true;
1054 break;
1055 }
1056
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001057 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001058 std::shared_ptr<const KeyEntry> keyEntry =
1059 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001060 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001061 if (isAppSwitchDue) {
1062 if (isAppSwitchKeyEvent(*keyEntry)) {
1063 resetPendingAppSwitchLocked(true);
1064 isAppSwitchDue = false;
1065 } else if (dropReason == DropReason::NOT_DROPPED) {
1066 dropReason = DropReason::APP_SWITCH;
1067 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 }
1069 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001070 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001071 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001073 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1074 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 break;
1078 }
1079
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001080 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001081 std::shared_ptr<const MotionEntry> motionEntry =
1082 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001083 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001084 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1085 dropReason = DropReason::APP_SWITCH;
1086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001088 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001089 // The event is stale. However, only drop stale events if there isn't an ongoing
1090 // gesture. That would allow us to complete the processing of the current stroke.
1091 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1092 if (touchStateIt != mTouchStatesByDisplay.end()) {
1093 const TouchState& touchState = touchStateIt->second;
1094 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1095 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1096 dropReason = DropReason::STALE;
1097 }
1098 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001100 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1101 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001103 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 }
Chris Yef59a2f42020-10-16 12:55:26 -07001106
1107 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001108 std::shared_ptr<const SensorEntry> sensorEntry =
1109 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001110 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001111 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1112 dropReason = DropReason::APP_SWITCH;
1113 }
Chris Yef59a2f42020-10-16 12:55:26 -07001114 }
1115 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1116 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1117 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1118 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1119 dropReason = DropReason::STALE;
1120 }
1121 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1122 done = true;
1123 break;
1124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126
1127 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001129 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
Michael Wright3a981722015-06-10 15:26:13 +01001131 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132
1133 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001134 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 }
1136}
1137
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001138bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001139 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001140}
1141
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001142/**
1143 * Return true if the events preceding this incoming motion event should be dropped
1144 * Return false otherwise (the default behaviour)
1145 */
1146bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001147 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001148 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001149
1150 // Optimize case where the current application is unresponsive and the user
1151 // decides to touch a window in a different application.
1152 // If the application takes too long to catch up then we drop all events preceding
1153 // the touch into the other window.
1154 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001155 const int32_t displayId = motionEntry.displayId;
1156 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001157 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001158
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001159 sp<WindowInfoHandle> touchedWindowHandle =
1160 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001161 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001162 touchedWindowHandle->getApplicationToken() !=
1163 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001164 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001165 ALOGI("Pruning input queue because user touched a different application while waiting "
1166 "for %s",
1167 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001168 return true;
1169 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001170
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001171 // Alternatively, maybe there's a spy window that could handle this event.
1172 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1173 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1174 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001175 const std::shared_ptr<Connection> connection =
1176 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001177 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001178 // This spy window could take more input. Drop all events preceding this
1179 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001180 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001181 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001182 mAwaitedFocusedApplication->getName().c_str());
1183 return true;
1184 }
1185 }
1186 }
1187
1188 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1189 // yet been processed by some connections, the dispatcher will wait for these motion
1190 // events to be processed before dispatching the key event. This is because these motion events
1191 // may cause a new window to be launched, which the user might expect to receive focus.
1192 // To prevent waiting forever for such events, just send the key to the currently focused window
1193 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1194 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1195 "just send the pending key event to the focused window.");
1196 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001197 }
1198 return false;
1199}
1200
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001202 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001204 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 traceInboundQueueLengthLocked();
1206
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001208 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001209 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1210 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 // Optimize app switch latency.
1212 // If the application takes too long to catch up then we drop all events preceding
1213 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001215
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001216 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001217 if (isAppSwitchKeyEvent(keyEntry)) {
1218 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
1219 mAppSwitchSawKeyDown = true;
1220 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
1221 if (mAppSwitchSawKeyDown) {
1222 if (DEBUG_APP_SWITCH) {
1223 ALOGD("App switch is pending!");
1224 }
1225 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
1226 mAppSwitchSawKeyDown = false;
1227 needWake = true;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001228 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 }
1230 }
1231 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001232 // If a new up event comes in, and the pending event with same key code has been asked
1233 // to try again later because of the policy. We have to reset the intercept key wake up
1234 // time for it may have been handled in the policy and could be dropped.
1235 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1236 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001237 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001238 if (pendingKey.keyCode == keyEntry.keyCode &&
1239 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001240 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1241 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001242 pendingKey.interceptKeyWakeupTime = 0;
1243 needWake = true;
1244 }
1245 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 break;
1247 }
1248
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001249 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001250 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1251 "Unexpected untrusted event.");
Prabir Pradhan24047542023-11-02 17:14:59 +00001252 if (shouldPruneInboundQueueLocked(static_cast<const MotionEntry&>(entry))) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001258 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001259 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1260 break;
1261 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001262 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001263 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001264 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001265 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001266 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1267 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001268 // nothing to do
1269 break;
1270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 }
1272
1273 return needWake;
1274}
1275
Prabir Pradhan24047542023-11-02 17:14:59 +00001276void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001277 // Do not store sensor event in recent queue to avoid flooding the queue.
1278 if (entry->type != EventEntry::Type::SENSOR) {
1279 mRecentQueue.push_back(entry);
1280 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001281 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001282 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 }
1284}
1285
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001286sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1287 bool isStylus,
1288 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001290 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001291 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001292 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001293 continue;
1294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001296 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001297 if (!info.isSpy() &&
1298 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001299 return windowHandle;
1300 }
1301 }
1302 return nullptr;
1303}
1304
1305std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001306 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001307 if (touchedWindow == nullptr) {
1308 return {};
1309 }
1310 // Traverse windows from front to back until we encounter the touched window.
1311 std::vector<InputTarget> outsideTargets;
1312 const auto& windowHandles = getWindowHandlesLocked(displayId);
1313 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1314 if (windowHandle == touchedWindow) {
1315 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1316 // below the touched window will not get ACTION_OUTSIDE event.
1317 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001318 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001319
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001320 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001321 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001322 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1323 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001324 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1325 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001326 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 }
1328 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001329 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330}
1331
Prabir Pradhand65552b2021-10-07 11:23:50 -07001332std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001333 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001334 // Traverse windows from front to back and gather the touched spy windows.
1335 std::vector<sp<WindowInfoHandle>> spyWindows;
1336 const auto& windowHandles = getWindowHandlesLocked(displayId);
1337 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1338 const WindowInfo& info = *windowHandle->getInfo();
1339
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001340 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001341 continue;
1342 }
1343 if (!info.isSpy()) {
1344 // The first touched non-spy window was found, so return the spy windows touched so far.
1345 return spyWindows;
1346 }
1347 spyWindows.push_back(windowHandle);
1348 }
1349 return spyWindows;
1350}
1351
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001352void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 const char* reason;
1354 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001355 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001356 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001357 ALOGD("Dropped event because policy consumed it.");
1358 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001359 reason = "inbound event was dropped because the policy consumed it";
1360 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001361 case DropReason::DISABLED:
1362 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001363 ALOGI("Dropped event because input dispatch is disabled.");
1364 }
1365 reason = "inbound event was dropped because input dispatch is disabled";
1366 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001367 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 ALOGI("Dropped event because of pending overdue app switch.");
1369 reason = "inbound event was dropped because of pending overdue app switch";
1370 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001371 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001372 ALOGI("Dropped event because the current application is not responding and the user "
1373 "has started interacting with a different application.");
1374 reason = "inbound event was dropped because the current application is not responding "
1375 "and the user has started interacting with a different application";
1376 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001377 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001378 ALOGI("Dropped event because it is stale.");
1379 reason = "inbound event was dropped because it is stale";
1380 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001381 case DropReason::NO_POINTER_CAPTURE:
1382 ALOGI("Dropped event because there is no window with Pointer Capture.");
1383 reason = "inbound event was dropped because there is no window with Pointer Capture";
1384 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001385 case DropReason::NOT_DROPPED: {
1386 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 }
1390
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001392 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001393 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001395 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001397 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1399 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001400 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 synthesizeCancelationEventsForAllConnectionsLocked(options);
1402 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001403 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1404 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001405 synthesizeCancelationEventsForAllConnectionsLocked(options);
1406 }
1407 break;
1408 }
Chris Yef59a2f42020-10-16 12:55:26 -07001409 case EventEntry::Type::SENSOR: {
1410 break;
1411 }
arthurhungb89ccb02020-12-30 16:19:01 +08001412 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1413 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001414 break;
1415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001416 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001417 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001418 case EventEntry::Type::CONFIGURATION_CHANGED:
1419 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001420 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001421 break;
1422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424}
1425
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001426static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1428 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1432 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1433 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1434 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435}
1436
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001437bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001438 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439}
1440
1441void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001442 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001444 if (DEBUG_APP_SWITCH) {
1445 if (handled) {
1446 ALOGD("App switch has arrived.");
1447 } else {
1448 ALOGD("App switch was abandoned.");
1449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451}
1452
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001454 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455}
1456
Prabir Pradhancef936d2021-07-21 16:17:52 +00001457bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001458 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 return false;
1460 }
1461
1462 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001463 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001464 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001465 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1466 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001467 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 return true;
1469}
1470
Prabir Pradhancef936d2021-07-21 16:17:52 +00001471void InputDispatcher::postCommandLocked(Command&& command) {
1472 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473}
1474
1475void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001476 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001477 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001478 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 releaseInboundEventLocked(entry);
1480 }
1481 traceInboundQueueLengthLocked();
1482}
1483
1484void InputDispatcher::releasePendingEventLocked() {
1485 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001487 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489}
1490
Prabir Pradhan24047542023-11-02 17:14:59 +00001491void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001492 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001493 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001494 if (DEBUG_DISPATCH_CYCLE) {
1495 ALOGD("Injected inbound event was dropped.");
1496 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001497 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 }
1499 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001500 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503}
1504
1505void InputDispatcher::resetKeyRepeatLocked() {
1506 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001507 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509}
1510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001512 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513
Michael Wright2e732952014-09-24 13:26:59 -07001514 uint32_t policyFlags = entry->policyFlags &
1515 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001517 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001518 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1519 currentTime, entry->deviceId, entry->source,
1520 entry->displayId, policyFlags, entry->action, entry->flags,
1521 entry->keyCode, entry->scanCode, entry->metaState,
1522 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001524 newEntry->syntheticRepeat = true;
1525 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528}
1529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001530bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001532 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1533 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
1536 // Reset key repeating in case a keyboard device was added or removed or something.
1537 resetKeyRepeatLocked();
1538
1539 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001540 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1541 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001542 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001543 };
1544 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 return true;
1546}
1547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1549 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001550 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1551 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1552 entry.deviceId);
1553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554
liushenxiang42232912021-05-21 20:24:09 +08001555 // Reset key repeating in case a keyboard device was disabled or enabled.
1556 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1557 resetKeyRepeatLocked();
1558 }
1559
Michael Wrightfb04fd52022-11-24 22:31:11 +00001560 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001561 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001563
1564 // Remove all active pointers from this device
1565 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1566 touchState.removeAllPointersForDevice(entry.deviceId);
1567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 return true;
1569}
1570
Vishnu Nairad321cd2020-08-20 16:40:21 -07001571void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001572 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001573 if (mPendingEvent != nullptr) {
1574 // Move the pending event to the front of the queue. This will give the chance
1575 // for the pending event to get dispatched to the newly focused window
1576 mInboundQueue.push_front(mPendingEvent);
1577 mPendingEvent = nullptr;
1578 }
1579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 std::unique_ptr<FocusEntry> focusEntry =
1581 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1582 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001583
1584 // This event should go to the front of the queue, but behind all other focus events
1585 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001586 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1587 [](const std::shared_ptr<const EventEntry>& event) {
1588 return event->type == EventEntry::Type::FOCUS;
1589 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001590
1591 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001592 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001593}
1594
Prabir Pradhan24047542023-11-02 17:14:59 +00001595void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1596 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001597 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001598 if (channel == nullptr) {
1599 return; // Window has gone away
1600 }
1601 InputTarget target;
1602 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001603 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001604 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1605 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001606 std::string reason = std::string("reason=").append(entry->reason);
1607 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001608 dispatchEventLocked(currentTime, entry, {target});
1609}
1610
Prabir Pradhan99987712020-11-10 18:43:05 -08001611void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001612 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001613 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001614 dropReason = DropReason::NOT_DROPPED;
1615
Prabir Pradhan99987712020-11-10 18:43:05 -08001616 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001617 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001618
1619 if (entry->pointerCaptureRequest.enable) {
1620 // Enable Pointer Capture.
1621 if (haveWindowWithPointerCapture &&
1622 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001623 // This can happen if pointer capture is disabled and re-enabled before we notify the
1624 // app of the state change, so there is no need to notify the app.
1625 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1626 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001627 }
1628 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001629 // This can happen if a window requests capture and immediately releases capture.
1630 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001631 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001632 return;
1633 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001634 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1635 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1636 return;
1637 }
1638
Vishnu Nairc519ff72021-01-21 08:23:08 -08001639 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001640 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1641 mWindowTokenWithPointerCapture = token;
1642 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001643 // Disable Pointer Capture.
1644 // We do not check if the sequence number matches for requests to disable Pointer Capture
1645 // for two reasons:
1646 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1647 // to disable capture with the same sequence number: one generated by
1648 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1649 // Capture being disabled in InputReader.
1650 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1651 // actual Pointer Capture state that affects events being generated by input devices is
1652 // in InputReader.
1653 if (!haveWindowWithPointerCapture) {
1654 // Pointer capture was already forcefully disabled because of focus change.
1655 dropReason = DropReason::NOT_DROPPED;
1656 return;
1657 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001658 token = mWindowTokenWithPointerCapture;
1659 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001660 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001661 setPointerCaptureLocked(false);
1662 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001663 }
1664
1665 auto channel = getInputChannelLocked(token);
1666 if (channel == nullptr) {
1667 // Window has gone away, clean up Pointer Capture state.
1668 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001669 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001670 setPointerCaptureLocked(false);
1671 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001672 return;
1673 }
1674 InputTarget target;
1675 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001676 entry->dispatchInProgress = true;
1677 dispatchEventLocked(currentTime, entry, {target});
1678
1679 dropReason = DropReason::NOT_DROPPED;
1680}
1681
Prabir Pradhan24047542023-11-02 17:14:59 +00001682void InputDispatcher::dispatchTouchModeChangeLocked(
1683 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001684 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001685 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001686 if (windowHandles.empty()) {
1687 return;
1688 }
1689 const std::vector<InputTarget> inputTargets =
1690 getInputTargetsFromWindowHandlesLocked(windowHandles);
1691 if (inputTargets.empty()) {
1692 return;
1693 }
1694 entry->dispatchInProgress = true;
1695 dispatchEventLocked(currentTime, entry, inputTargets);
1696}
1697
1698std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1699 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1700 std::vector<InputTarget> inputTargets;
1701 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001702 const sp<IBinder>& token = handle->getToken();
1703 if (token == nullptr) {
1704 continue;
1705 }
1706 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1707 if (channel == nullptr) {
1708 continue; // Window has gone away
1709 }
1710 InputTarget target;
1711 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001712 inputTargets.push_back(target);
1713 }
1714 return inputTargets;
1715}
1716
Prabir Pradhan24047542023-11-02 17:14:59 +00001717bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001718 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001720 if (!entry->dispatchInProgress) {
1721 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1722 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1723 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1724 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001725 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 // We have seen two identical key downs in a row which indicates that the device
1727 // driver is automatically generating key repeats itself. We take note of the
1728 // repeat here, but we disable our own next key repeat timer since it is clear that
1729 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001730 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1731 // Make sure we don't get key down from a different device. If a different
1732 // device Id has same key pressed down, the new device Id will replace the
1733 // current one to hold the key repeat with repeat count reset.
1734 // In the future when got a KEY_UP on the device id, drop it and do not
1735 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1737 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001738 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 } else {
1740 // Not a repeat. Save key down state in case we do see a repeat later.
1741 resetKeyRepeatLocked();
1742 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1743 }
1744 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001745 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1746 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001747 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001748 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001749 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1750 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 resetKeyRepeatLocked();
1753 }
1754
1755 if (entry->repeatCount == 1) {
1756 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1757 } else {
1758 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1759 }
1760
1761 entry->dispatchInProgress = true;
1762
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 }
1765
1766 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001767 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 if (currentTime < entry->interceptKeyWakeupTime) {
1769 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1770 *nextWakeupTime = entry->interceptKeyWakeupTime;
1771 }
1772 return false; // wait until next wakeup
1773 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001774 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 entry->interceptKeyWakeupTime = 0;
1776 }
1777
1778 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001779 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001781 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001782 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001783
1784 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1785 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1786 };
1787 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001788 // Poke user activity for keys not passed to user
1789 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 return false; // wait for the command to run
1791 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001792 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001794 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001795 if (*dropReason == DropReason::NOT_DROPPED) {
1796 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
1798 }
1799
1800 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001801 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001803 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1804 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001805 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001806 // Poke user activity for undispatched keys
1807 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 return true;
1809 }
1810
1811 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001812 InputEventInjectionResult injectionResult;
1813 sp<WindowInfoHandle> focusedWindow =
1814 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1815 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001816 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 return false;
1818 }
1819
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001820 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 return true;
1823 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001824 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1825
1826 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001827 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1828 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001830 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832
1833 // Dispatch the key.
1834 dispatchEventLocked(currentTime, entry, inputTargets);
1835 return true;
1836}
1837
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001839 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1840 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1841 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1842 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1843 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1844 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1845 entry.metaState, entry.repeatCount, entry.downTime);
1846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847}
1848
Prabir Pradhancef936d2021-07-21 16:17:52 +00001849void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001850 const std::shared_ptr<const SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001851 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1853 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1854 "source=0x%x, sensorType=%s",
1855 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001856 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001857 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001858 auto command = [this, entry]() REQUIRES(mLock) {
1859 scoped_unlock unlock(mLock);
1860
1861 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001862 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001863 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001864 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1865 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001866 };
1867 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001868}
1869
1870bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1872 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001873 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001874 }
Chris Yef59a2f42020-10-16 12:55:26 -07001875 { // acquire lock
1876 std::scoped_lock _l(mLock);
1877
1878 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001879 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001880 if (entry->type == EventEntry::Type::SENSOR) {
1881 it = mInboundQueue.erase(it);
1882 releaseInboundEventLocked(entry);
1883 }
1884 }
1885 }
1886 return true;
1887}
1888
Prabir Pradhan24047542023-11-02 17:14:59 +00001889bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1890 std::shared_ptr<const MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001891 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001892 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001894 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 entry->dispatchInProgress = true;
1896
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001897 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899
1900 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001901 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001902 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1904 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 return true;
1906 }
1907
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001908 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909
1910 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001911 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 if (isPointerEvent) {
1915 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001916
1917 if (mDragState &&
1918 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1919 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1920 pilferPointersLocked(mDragState->dragWindow->getToken());
1921 }
1922
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001923 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001924 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001925 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1926 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 } else {
1928 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001929 sp<WindowInfoHandle> focusedWindow =
1930 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1931 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1932 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001933 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1934 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1935 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 return false;
1940 }
1941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001942 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001943 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001944 return true;
1945 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001946 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001947 CancelationOptions::Mode mode(
1948 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1949 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001950 CancelationOptions options(mode, "input event injection failed");
1951 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 return true;
1953 }
1954
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001955 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957
1958 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 dispatchEventLocked(currentTime, entry, inputTargets);
1960 return true;
1961}
1962
chaviw98318de2021-05-19 16:45:23 -05001963void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001964 bool isExiting, const int32_t rawX,
1965 const int32_t rawY) {
1966 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001967 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001968 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1969 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001970
1971 enqueueInboundEventLocked(std::move(dragEntry));
1972}
1973
Prabir Pradhan24047542023-11-02 17:14:59 +00001974void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
1975 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08001976 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1977 if (channel == nullptr) {
1978 return; // Window has gone away
1979 }
1980 InputTarget target;
1981 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08001982 entry->dispatchInProgress = true;
1983 dispatchEventLocked(currentTime, entry, {target});
1984}
1985
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001987 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001988 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001990 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 "metaState=0x%x, buttonState=0x%x,"
1992 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001993 prefix, entry.eventTime, entry.deviceId,
1994 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1995 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1996 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1997 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07001999 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002000 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002001 "x=%f, y=%f, pressure=%f, size=%f, "
2002 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2003 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002004 i, entry.pointerProperties[i].id,
2005 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002006 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017}
2018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002019void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002020 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002022 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002023 if (DEBUG_DISPATCH_CYCLE) {
2024 ALOGD("dispatchEventToCurrentInputTargets");
2025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002027 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002033 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002034 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002035 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002036 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002037 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002039 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2040 LOG(INFO) << "Dropping event delivery to target with channel "
2041 << inputTarget.inputChannel->getName()
2042 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045 }
2046}
2047
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002048void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2050 // If the policy decides to close the app, we will get a channel removal event via
2051 // unregisterInputChannel, and will clean up the connection that way. We are already not
2052 // sending new pointers to the connection when it blocked, but focused events will continue to
2053 // pile up.
2054 ALOGW("Canceling events for %s because it is unresponsive",
2055 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002056 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002057 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002058 "application not responding");
2059 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061}
2062
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002064 if (DEBUG_FOCUS) {
2065 ALOGD("Resetting ANR timeouts.");
2066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
2068 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002070 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071}
2072
Tiger Huang721e26f2018-07-24 22:26:19 +08002073/**
2074 * Get the display id that the given event should go to. If this event specifies a valid display id,
2075 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2076 * Focused display is the display that the user most recently interacted with.
2077 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002079 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002081 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2083 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 break;
2085 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2088 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 break;
2090 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002091 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002092 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002093 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002094 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002095 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002096 case EventEntry::Type::SENSOR:
2097 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002098 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002099 return ADISPLAY_ID_NONE;
2100 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002101 }
2102 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2103}
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2106 const char* focusedWindowName) {
2107 if (mAnrTracker.empty()) {
2108 // already processed all events that we waited for
2109 mKeyIsWaitingForEventsTimeout = std::nullopt;
2110 return false;
2111 }
2112
2113 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2114 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002115 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002116 mKeyIsWaitingForEventsTimeout = currentTime +
2117 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2118 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 return true;
2120 }
2121
2122 // We still have pending events, and already started the timer
2123 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2124 return true; // Still waiting
2125 }
2126
2127 // Waited too long, and some connection still hasn't processed all motions
2128 // Just send the key to the focused window
2129 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2130 focusedWindowName);
2131 mKeyIsWaitingForEventsTimeout = std::nullopt;
2132 return false;
2133}
2134
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2136 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2137 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002138 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
Tiger Huang721e26f2018-07-24 22:26:19 +08002141 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002142 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002143 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002144 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2145
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 // If there is no currently focused window and no focused application
2147 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002148 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2149 ALOGI("Dropping %s event because there is no focused window or focused application in "
2150 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002151 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002152 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
Vishnu Nair062a8672021-09-03 16:07:44 -07002155 // Drop key events if requested by input feature
2156 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002157 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002158 }
2159
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2161 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2162 // start interacting with another application via touch (app switch). This code can be removed
2163 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2164 // an app is expected to have a focused window.
2165 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2166 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2167 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002168 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2169 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2170 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002171 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002172 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 ALOGW("Waiting because no window has focus but %s may eventually add a "
2174 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002175 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 outInjectionResult = InputEventInjectionResult::PENDING;
2178 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2180 // Already raised ANR. Drop the event
2181 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002182 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 } else {
2185 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 outInjectionResult = InputEventInjectionResult::PENDING;
2187 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 }
2189 }
2190
2191 // we have a valid, non-null focused window
2192 resetNoFocusedWindowTimeoutLocked();
2193
Prabir Pradhan5735a322022-04-11 17:23:34 +00002194 // Verify targeted injection.
2195 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2196 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2198 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002201 if (focusedWindowHandle->getInfo()->inputConfig.test(
2202 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002203 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002204 outInjectionResult = InputEventInjectionResult::PENDING;
2205 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 }
2207
2208 // If the event is a key event, then we must wait for all previous events to
2209 // complete before delivering it because previous events may have the
2210 // side-effect of transferring focus to a different window and we want to
2211 // ensure that the following keys are sent to the new window.
2212 //
2213 // Suppose the user touches a button in a window then immediately presses "A".
2214 // If the button causes a pop-up window to appear then we want to ensure that
2215 // the "A" key is delivered to the new pop-up window. This is because users
2216 // often anticipate pending UI changes when typing on a keyboard.
2217 // To obtain this behavior, we must serialize key events with respect to all
2218 // prior input events.
2219 if (entry.type == EventEntry::Type::KEY) {
2220 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2221 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002222 outInjectionResult = InputEventInjectionResult::PENDING;
2223 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2228 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229}
2230
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002231/**
2232 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2233 * that are currently unresponsive.
2234 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002235std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2236 const std::vector<Monitor>& monitors) const {
2237 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002238 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002239 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002240 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002241 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 if (connection == nullptr) {
2243 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002244 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 return false;
2246 }
2247 if (!connection->responsive) {
2248 ALOGW("Unresponsive monitor %s will not get the new gesture",
2249 connection->inputChannel->getName().c_str());
2250 return false;
2251 }
2252 return true;
2253 });
2254 return responsiveMonitors;
2255}
2256
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002257std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002258 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002259 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002262 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 // For security reasons, we defer updating the touch state until we are sure that
2264 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 const int32_t displayId = entry.displayId;
2266 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002267 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268
2269 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002270 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 // Copy current touch state into tempTouchState.
2273 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2274 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002275 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2278 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002279 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002280 }
2281
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002282 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283
2284 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2285 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2286 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002287 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2288 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002289 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002290 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2291 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002292 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2293 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2294 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002295 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002296
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002297 if (newGesture) {
2298 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002299 }
2300
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002301 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2302 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2303 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002306 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002307 if (wasDown) {
2308 // Started hovering, but the device is already down: reject the hover event
2309 LOG(ERROR) << "Got hover event " << entry.getDescription()
2310 << " but the device is already down " << oldState->dump();
2311 outInjectionResult = InputEventInjectionResult::FAILED;
2312 return {};
2313 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002314 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2315 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002316 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002317 }
2318
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2320 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002321 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002322 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002323 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002324 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2325 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002326 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002327 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002328 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002329
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002330 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002331 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002334 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002335 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002337 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002338 }
2339
Prabir Pradhan5735a322022-04-11 17:23:34 +00002340 // Verify targeted injection.
2341 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2342 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002343 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002344 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002345 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002346 }
2347
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002348 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002350 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2351 // New window supports splitting, but we should never split mouse events.
2352 isSplit = !isFromMouse;
2353 } else if (isSplit) {
2354 // New window does not support splitting but we have already split events.
2355 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002356 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2357 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002358 newTouchedWindowHandle = nullptr;
2359 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002360 } else {
2361 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002362 // be delivered to a new window which supports split touch. Pointers from a mouse device
2363 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002364 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002365 }
2366
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002367 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002368 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002369 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002370 // Process the foreground window first so that it is the first to receive the event.
2371 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002372 }
2373
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002374 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002375 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2376 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002378 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002379 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002380 }
2381
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002382 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002383 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 continue;
2385 }
2386
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002387 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002388 // The "windowHandle" is the target of this hovering pointer.
2389 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002390 }
2391
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002393 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002394
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002395 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2396 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002397 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002398 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399
2400 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002401 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002402 }
2403 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002404 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002405 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002406 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002407 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002408
2409 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002410
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002411 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002412 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002413 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002414 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2415 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002416 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
2417 targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002418 isDownOrPointerDown
2419 ? std::make_optional(entry.eventTime)
2420 : std::nullopt);
2421 // If this is the pointer going down and the touched window has a wallpaper
2422 // then also add the touched wallpaper windows so they are locked in for the
2423 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2424 // SCROLL because the wallpaper engine only supports touch events. We would need to
2425 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2426 // handle these events.
2427 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002428 windowHandle->getInfo()->inputConfig.test(
2429 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2430 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2431 if (wallpaper != nullptr) {
2432 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2433 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002434 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002435 if (isSplit) {
2436 wallpaperFlags |= InputTarget::Flags::SPLIT;
2437 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002438 tempTouchState.addOrUpdateWindow(wallpaper,
2439 InputTarget::DispatchMode::AS_IS,
2440 wallpaperFlags, entry.deviceId, pointerIds,
2441 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002442 }
2443 }
2444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002446
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002447 // If a window is already pilfering some pointers, give it this new pointer as well and
2448 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2449 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002450 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002451 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2452 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002453 // This window is already pilfering some pointers, and this new pointer is also
2454 // going to it. Therefore, take over this pointer and don't give it to anyone
2455 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002456 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002457 }
2458 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002459
2460 // Restrict all pilfered pointers to the pilfering windows.
2461 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 } else {
2463 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2464
2465 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002466 if (!tempTouchState.isDown(entry.deviceId) &&
2467 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002468 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2469 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2470 << " is not down or we previously dropped the pointer down event in "
2471 << "display " << displayId << ": " << entry.getDescription();
2472 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002473 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002474 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 }
2476
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002477 // If the pointer is not currently hovering, then ignore the event.
2478 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2479 const int32_t pointerId = entry.pointerProperties[0].id;
2480 if (oldState == nullptr ||
2481 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2482 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2483 "display "
2484 << displayId << ": " << entry.getDescription();
2485 outInjectionResult = InputEventInjectionResult::FAILED;
2486 return {};
2487 }
2488 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2489 }
2490
arthurhung6d4bed92021-03-17 11:59:33 +08002491 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002492
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002494 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002495 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002496 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002497 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002498 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002499 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002500 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002501 sp<WindowInfoHandle> newTouchedWindowHandle =
2502 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002503
Prabir Pradhan5735a322022-04-11 17:23:34 +00002504 // Verify targeted injection.
2505 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2506 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002507 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002508 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002509 }
2510
Vishnu Nair062a8672021-09-03 16:07:44 -07002511 // Drop touch events if requested by input feature
2512 if (newTouchedWindowHandle != nullptr &&
2513 shouldDropInput(entry, newTouchedWindowHandle)) {
2514 newTouchedWindowHandle = nullptr;
2515 }
2516
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002517 if (newTouchedWindowHandle != nullptr &&
2518 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002519 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002520 oldTouchedWindowHandle->getName().c_str(),
2521 newTouchedWindowHandle->getName().c_str(), displayId);
2522
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002524 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002525 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002526 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002527
2528 const TouchedWindow& touchedWindow =
2529 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002530 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002531 InputTarget::DispatchMode::SLIPPERY_EXIT,
2532 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002533 touchedWindow.getDownTimeInTarget(entry.deviceId),
2534 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535
2536 // Make a slippery entrance into the new window.
2537 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002538 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002541 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002542 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002543 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002546 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002549 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002550 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002551 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 }
2553
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002554 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2555 InputTarget::DispatchMode::SLIPPERY_ENTER,
2556 targetFlags, entry.deviceId, pointerIds,
2557 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002558
2559 // Check if the wallpaper window should deliver the corresponding event.
2560 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002561 tempTouchState, entry.deviceId, pointerId, targets);
2562 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2563 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565 }
Arthur Hung96483742022-11-15 03:30:48 +00002566
2567 // Update the pointerIds for non-splittable when it received pointer down.
2568 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2569 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002570 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002571 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2572 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2573 // Ignore drag window for it should just track one pointer.
2574 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2575 continue;
2576 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002577 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2578 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2579 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002580 }
2581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
2583
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002584 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002585 {
2586 std::vector<TouchedWindow> hoveringWindows =
2587 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2588 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002589 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002590 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2591 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002592 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002593 if (!target) {
2594 continue;
2595 }
2596 // Hardcode to single hovering pointer for now.
2597 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2598 pointerIds.set(entry.pointerProperties[0].id);
2599 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2600 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603
Prabir Pradhan5735a322022-04-11 17:23:34 +00002604 // Ensure that all touched windows are valid for injection.
2605 if (entry.injectionState != nullptr) {
2606 std::string errs;
2607 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002608 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2609 if (err) errs += "\n - " + *err;
2610 }
2611 if (!errs.empty()) {
2612 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002613 "%s:%s",
2614 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002615 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002616 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002617 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002618 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002619
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002620 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2621 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002623 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002624 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002625 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002626 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002627 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002628 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002629 sp<WindowInfoHandle> targetWindow =
2630 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2631 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2632 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 }
2635 }
2636 }
2637 }
2638
Harry Cuttsb166c002023-05-09 13:06:05 +00002639 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2640 // only want the system UI to handle these gestures.
2641 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2642 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2643 if (isTouchpadNavGesture) {
2644 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2645 }
2646
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002647 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002648 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002649 std::bitset<MAX_POINTER_ID + 1> touchingPointers =
2650 touchedWindow.getTouchingPointers(entry.deviceId);
2651 if (touchingPointers.none()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002652 continue;
2653 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002654 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2655 touchedWindow.targetFlags, touchingPointers,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002656 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002657 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002658
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002659 // During targeted injection, only allow owned targets to receive events
2660 std::erase_if(targets, [&](const InputTarget& target) {
2661 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2662 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2663 if (err) {
2664 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2665 << ": " << (*err);
2666 return true;
2667 }
2668 return false;
2669 });
2670
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002671 if (targets.empty()) {
2672 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2673 outInjectionResult = InputEventInjectionResult::FAILED;
2674 return {};
2675 }
2676
2677 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2678 // window that is actually receiving the entire gesture.
2679 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002680 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002681 })) {
2682 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2683 << entry.getDescription();
2684 outInjectionResult = InputEventInjectionResult::FAILED;
2685 return {};
2686 }
2687
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002688 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
Prabir Pradhan502a7252023-12-01 16:11:24 +00002690 // Now that we have generated all of the input targets for this event, reset the dispatch
2691 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002692 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002693 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002694 }
2695
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002696 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002697 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002698 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002699 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002700 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002701 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002702 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002703 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2704 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002705 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2706 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2707 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 }
2709
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 // Save changes unless the action was scroll in which case the temporary touch
2711 // state was only valid for this one action.
2712 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002713 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002714 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002715 mTouchStatesByDisplay[displayId] = tempTouchState;
2716 } else {
2717 mTouchStatesByDisplay.erase(displayId);
2718 }
2719 }
2720
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002721 if (tempTouchState.windows.empty()) {
2722 mTouchStatesByDisplay.erase(displayId);
2723 }
2724
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002725 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726}
2727
arthurhung6d4bed92021-03-17 11:59:33 +08002728void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002729 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2730 // have an explicit reason to support it.
2731 constexpr bool isStylus = false;
2732
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002733 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002734 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002735 if (dropWindow) {
2736 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002737 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002738 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002739 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002740 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002741 }
2742 mDragState.reset();
2743}
2744
2745void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002746 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002747 return;
2748 }
2749
arthurhung6d4bed92021-03-17 11:59:33 +08002750 if (!mDragState->isStartDrag) {
2751 mDragState->isStartDrag = true;
2752 mDragState->isStylusButtonDownAtStart =
2753 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2754 }
2755
Arthur Hung54745652022-04-20 07:17:41 +00002756 // Find the pointer index by id.
2757 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002758 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002759 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2760 if (pointerProperties.id == mDragState->pointerId) {
2761 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002762 }
Arthur Hung54745652022-04-20 07:17:41 +00002763 }
arthurhung6d4bed92021-03-17 11:59:33 +08002764
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002765 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002766 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002767 }
2768
2769 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2770 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2771 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2772
2773 switch (maskedAction) {
2774 case AMOTION_EVENT_ACTION_MOVE: {
2775 // Handle the special case : stylus button no longer pressed.
2776 bool isStylusButtonDown =
2777 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2778 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2779 finishDragAndDrop(entry.displayId, x, y);
2780 return;
2781 }
2782
2783 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2784 // until we have an explicit reason to support it.
2785 constexpr bool isStylus = false;
2786
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002787 sp<WindowInfoHandle> hoverWindowHandle =
2788 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2789 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002790 // enqueue drag exit if needed.
2791 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2792 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2793 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002794 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002795 y);
2796 }
2797 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2798 }
2799 // enqueue drag location if needed.
2800 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002801 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002802 }
2803 break;
2804 }
2805
2806 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002807 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002808 break;
2809 }
2810 // The drag pointer is up.
2811 [[fallthrough]];
2812 case AMOTION_EVENT_ACTION_UP:
2813 finishDragAndDrop(entry.displayId, x, y);
2814 break;
2815 case AMOTION_EVENT_ACTION_CANCEL: {
2816 ALOGD("Receiving cancel when drag and drop.");
2817 sendDropWindowCommandLocked(nullptr, 0, 0);
2818 mDragState.reset();
2819 break;
2820 }
arthurhungb89ccb02020-12-30 16:19:01 +08002821 }
2822}
2823
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002824std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2825 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002826 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002827 std::optional<nsecs_t> firstDownTimeInTarget) const {
2828 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2829 if (inputChannel == nullptr) {
2830 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2831 return {};
2832 }
2833 InputTarget inputTarget;
2834 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002835 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002836 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002837 inputTarget.flags = targetFlags;
2838 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2839 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2840 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2841 if (displayInfoIt != mDisplayInfos.end()) {
2842 inputTarget.displayTransform = displayInfoIt->second.transform;
2843 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002844 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002845 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2846 }
2847 return inputTarget;
2848}
2849
chaviw98318de2021-05-19 16:45:23 -05002850void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002851 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002852 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002853 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002854 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002855 std::vector<InputTarget>::iterator it =
2856 std::find_if(inputTargets.begin(), inputTargets.end(),
2857 [&windowHandle](const InputTarget& inputTarget) {
2858 return inputTarget.inputChannel->getConnectionToken() ==
2859 windowHandle->getToken();
2860 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002861
chaviw98318de2021-05-19 16:45:23 -05002862 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002863
2864 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002865 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002866 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2867 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002868 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002869 return;
2870 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002871 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002872 it = inputTargets.end() - 1;
2873 }
2874
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002875 if (it->flags != targetFlags) {
2876 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2877 }
2878 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2879 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2880 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2881 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002882}
2883
2884void InputDispatcher::addPointerWindowTargetLocked(
2885 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002886 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2887 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2888 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002889 if (pointerIds.none()) {
2890 for (const auto& target : inputTargets) {
2891 LOG(INFO) << "Target: " << target;
2892 }
2893 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2894 return;
2895 }
2896 std::vector<InputTarget>::iterator it =
2897 std::find_if(inputTargets.begin(), inputTargets.end(),
2898 [&windowHandle](const InputTarget& inputTarget) {
2899 return inputTarget.inputChannel->getConnectionToken() ==
2900 windowHandle->getToken();
2901 });
2902
2903 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2904 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2905 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2906 // input targets for hovering pointers and for touching pointers.
2907 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2908 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002909 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002910 // Force the code below to create a new input target
2911 it = inputTargets.end();
2912 }
2913
2914 const WindowInfo* windowInfo = windowHandle->getInfo();
2915
2916 if (it == inputTargets.end()) {
2917 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002918 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2919 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002920 if (!target) {
2921 return;
2922 }
2923 inputTargets.push_back(*target);
2924 it = inputTargets.end() - 1;
2925 }
2926
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002927 if (it->dispatchMode != dispatchMode) {
2928 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2929 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2930 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002931 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002932 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2933 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002934 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002935 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002936 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002937 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2938 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002939
chaviw1ff3d1e2020-07-01 15:53:47 -07002940 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941}
2942
Michael Wright3dd60e22019-03-27 22:06:44 +00002943void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002944 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002945 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2946 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002947
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002948 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2949 InputTarget target;
2950 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002951 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2952 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002953 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2954 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002955 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002956 target.setDefaultPointerTransform(target.displayTransform);
2957 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
2959}
2960
Robert Carrc9bf1d32020-04-13 17:21:08 -07002961/**
2962 * Indicate whether one window handle should be considered as obscuring
2963 * another window handle. We only check a few preconditions. Actually
2964 * checking the bounds is left to the caller.
2965 */
chaviw98318de2021-05-19 16:45:23 -05002966static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2967 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002968 // Compare by token so cloned layers aren't counted
2969 if (haveSameToken(windowHandle, otherHandle)) {
2970 return false;
2971 }
2972 auto info = windowHandle->getInfo();
2973 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002974 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002975 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002976 } else if (otherInfo->alpha == 0 &&
2977 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002978 // Those act as if they were invisible, so we don't need to flag them.
2979 // We do want to potentially flag touchable windows even if they have 0
2980 // opacity, since they can consume touches and alter the effects of the
2981 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002982 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002983 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2984 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002985 } else if (info->ownerUid == otherInfo->ownerUid) {
2986 // If ownerUid is the same we don't generate occlusion events as there
2987 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002988 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002989 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002990 return false;
2991 } else if (otherInfo->displayId != info->displayId) {
2992 return false;
2993 }
2994 return true;
2995}
2996
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002997/**
2998 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2999 * untrusted, one should check:
3000 *
3001 * 1. If result.hasBlockingOcclusion is true.
3002 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3003 * BLOCK_UNTRUSTED.
3004 *
3005 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3006 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3007 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3008 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3009 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3010 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3011 *
3012 * If neither of those is true, then it means the touch can be allowed.
3013 */
3014InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003015 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3016 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003017 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003018 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003019 TouchOcclusionInfo info;
3020 info.hasBlockingOcclusion = false;
3021 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003022 info.obscuringUid = gui::Uid::INVALID;
3023 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003024 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003025 if (windowHandle == otherHandle) {
3026 break; // All future windows are below us. Exit early.
3027 }
chaviw98318de2021-05-19 16:45:23 -05003028 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003029 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3030 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003031 if (DEBUG_TOUCH_OCCLUSION) {
3032 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003033 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003034 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003035 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3036 // we perform the checks below to see if the touch can be propagated or not based on the
3037 // window's touch occlusion mode
3038 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3039 info.hasBlockingOcclusion = true;
3040 info.obscuringUid = otherInfo->ownerUid;
3041 info.obscuringPackage = otherInfo->packageName;
3042 break;
3043 }
3044 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003045 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003046 float opacity =
3047 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3048 // Given windows A and B:
3049 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3050 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3051 opacityByUid[uid] = opacity;
3052 if (opacity > info.obscuringOpacity) {
3053 info.obscuringOpacity = opacity;
3054 info.obscuringUid = uid;
3055 info.obscuringPackage = otherInfo->packageName;
3056 }
3057 }
3058 }
3059 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003060 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003061 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003062 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 return info;
3064}
3065
chaviw98318de2021-05-19 16:45:23 -05003066std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003067 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003068 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003069 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3070 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3071 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003072 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003073 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003074 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3075 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003076 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3077 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3078 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003079 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003080}
3081
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003082bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3083 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003084 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3085 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003086 return false;
3087 }
3088 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003089 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003090 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003091 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003092 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3093 return false;
3094 }
3095 return true;
3096}
3097
chaviw98318de2021-05-19 16:45:23 -05003098bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003101 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3102 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003103 if (windowHandle == otherHandle) {
3104 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 }
chaviw98318de2021-05-19 16:45:23 -05003106 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003107 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003108 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 return true;
3110 }
3111 }
3112 return false;
3113}
3114
chaviw98318de2021-05-19 16:45:23 -05003115bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003116 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003117 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3118 const WindowInfo* windowInfo = windowHandle->getInfo();
3119 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003120 if (windowHandle == otherHandle) {
3121 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003122 }
chaviw98318de2021-05-19 16:45:23 -05003123 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003124 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003125 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003126 return true;
3127 }
3128 }
3129 return false;
3130}
3131
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003132std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003133 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003134 if (applicationHandle != nullptr) {
3135 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003136 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 } else {
3138 return applicationHandle->getName();
3139 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003140 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003141 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003143 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
3145}
3146
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003148 if (!isUserActivityEvent(eventEntry)) {
3149 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003150 return;
3151 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003152 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003153 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003154 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003155 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003156 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003157 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003158 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160 }
3161
3162 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003163 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003164 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003165 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3166 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 return;
3168 }
Josep del Riob3981622023-04-18 15:49:45 +00003169 if (windowDisablingUserActivityInfo != nullptr) {
3170 if (DEBUG_DISPATCH_CYCLE) {
3171 ALOGD("Not poking user activity: disabled by window '%s'.",
3172 windowDisablingUserActivityInfo->name.c_str());
3173 }
3174 return;
3175 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003176 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 eventType = USER_ACTIVITY_EVENT_TOUCH;
3178 }
3179 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003182 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3183 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 return;
3185 }
Josep del Riob3981622023-04-18 15:49:45 +00003186 // If the key code is unknown, we don't consider it user activity
3187 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3188 return;
3189 }
3190 // Don't inhibit events that were intercepted or are not passed to
3191 // the apps, like system shortcuts
3192 if (windowDisablingUserActivityInfo != nullptr &&
3193 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3194 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3195 if (DEBUG_DISPATCH_CYCLE) {
3196 ALOGD("Not poking user activity: disabled by window '%s'.",
3197 windowDisablingUserActivityInfo->name.c_str());
3198 }
3199 return;
3200 }
3201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 eventType = USER_ACTIVITY_EVENT_BUTTON;
3203 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003205 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003206 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003207 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003208 break;
3209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211
Prabir Pradhancef936d2021-07-21 16:17:52 +00003212 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3213 REQUIRES(mLock) {
3214 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003215 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003216 };
3217 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218}
3219
3220void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003221 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003222 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003223 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003224 ATRACE_NAME_IF(ATRACE_ENABLED(),
3225 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3226 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003227 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003228 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003229 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003230 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003231 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003232 inputTarget.getPointerInfoString().c_str());
3233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234
3235 // Skip this event if the connection status is not normal.
3236 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003237 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003238 if (DEBUG_DISPATCH_CYCLE) {
3239 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003240 connection->getInputChannelName().c_str(),
3241 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 return;
3244 }
3245
3246 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003247 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003248 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003249 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003250 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003252 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003253 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003254 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3255 logDispatchStateLocked();
3256 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3257 "target on connection "
3258 << connection->getInputChannelName() << " for "
3259 << originalMotionEntry.getDescription();
3260 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003261 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003262 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3263 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 if (!splitMotionEntry) {
3265 return; // split event was dropped
3266 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003267 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3268 std::string reason = std::string("reason=pointer cancel on split window");
3269 android_log_event_list(LOGTAG_INPUT_CANCEL)
3270 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3271 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003272 if (DEBUG_FOCUS) {
3273 ALOGD("channel '%s' ~ Split motion event.",
3274 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003275 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003276 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003277 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3278 std::move(splitMotionEntry),
3279 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 return;
3281 }
3282 }
3283
3284 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003285 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3286 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287}
3288
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003289void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3290 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3291 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003292 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003293 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3294 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003295 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003296
hongzuo liu95785e22022-09-06 02:51:35 +00003297 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003299 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
3301 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003302 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 startDispatchCycleLocked(currentTime, connection);
3304 }
3305}
3306
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003307void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003308 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003309 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // This is a new event.
3311 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003312 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003313 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003315 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3316 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003317 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003319 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003320 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003321 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3322 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003323 LOG(WARNING) << "channel " << connection->getInputChannelName()
3324 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 return; // skip the inconsistent event
3326 }
3327 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003330 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003331 std::shared_ptr<const MotionEntry> resolvedMotion =
3332 std::static_pointer_cast<const MotionEntry>(eventEntry);
3333 {
3334 // Determine the resolved motion entry.
3335 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3336 int32_t resolvedAction = motionEntry.action;
3337 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003339 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003340 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003341 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003342 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003343 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003344 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003345 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003346 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003347 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003348 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3349 }
3350 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3351 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3352 motionEntry.displayId)) {
3353 if (DEBUG_DISPATCH_CYCLE) {
3354 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3355 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3356 "enter event";
3357 }
3358 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3359 }
3360
3361 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3362 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3363 }
3364 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3365 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3366 }
3367 if (dispatchEntry->targetFlags.test(
3368 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3369 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3370 }
3371
3372 dispatchEntry->resolvedFlags = resolvedFlags;
3373 if (resolvedAction != motionEntry.action) {
3374 // Generate a new MotionEntry with a new eventId using the resolved action and
3375 // flags.
3376 resolvedMotion =
3377 std::make_shared<MotionEntry>(mIdGenerator.nextId(),
3378 motionEntry.injectionState,
3379 motionEntry.eventTime,
3380 motionEntry.deviceId, motionEntry.source,
3381 motionEntry.displayId,
3382 motionEntry.policyFlags, resolvedAction,
3383 motionEntry.actionButton, resolvedFlags,
3384 motionEntry.metaState,
3385 motionEntry.buttonState,
3386 motionEntry.classification,
3387 motionEntry.edgeFlags,
3388 motionEntry.xPrecision,
3389 motionEntry.yPrecision,
3390 motionEntry.xCursorPosition,
3391 motionEntry.yCursorPosition,
3392 motionEntry.downTime,
3393 motionEntry.pointerProperties,
3394 motionEntry.pointerCoords);
3395 if (ATRACE_ENABLED()) {
3396 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3397 ") to MotionEvent(id=0x%" PRIx32 ").",
3398 motionEntry.id, resolvedMotion->id);
3399 ATRACE_NAME(message.c_str());
3400 }
3401
3402 // Set the resolved motion entry in the DispatchEntry.
3403 dispatchEntry->eventEntry = resolvedMotion;
3404 eventEntry = resolvedMotion;
3405 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003408 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3409 // devices being active at the same time in the same window, so if a new device is
3410 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003411 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003412 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003413 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003414 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003415 << connection->getInputChannelName() << " with event "
3416 << cancelEvent->getDescription();
3417 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3418 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003419 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003420
3421 // Send these cancel events to the queue before sending the event from the new
3422 // device.
3423 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3424 }
3425
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003426 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003428 LOG(WARNING) << "channel " << connection->getInputChannelName()
3429 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003430 return; // skip the inconsistent event
3431 }
3432
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003433 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3434 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003435 // Skip reporting pointer down outside focus to the policy.
3436 break;
3437 }
3438
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003439 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003440 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441
3442 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003444 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003445 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003446 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3447 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003448 break;
3449 }
Chris Yef59a2f42020-10-16 12:55:26 -07003450 case EventEntry::Type::SENSOR: {
3451 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3452 break;
3453 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003454 case EventEntry::Type::CONFIGURATION_CHANGED:
3455 case EventEntry::Type::DEVICE_RESET: {
3456 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003457 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003458 break;
3459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460 }
3461
3462 // Remember that we are waiting for this dispatch to complete.
3463 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003464 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 }
3466
3467 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003468 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003469 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003470}
3471
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003472/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003473 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003475 * The first role is to log input interaction with windows, which helps determine what the user was
3476 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3477 * that user started interacting with launcher window, as well as any other window that received
3478 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3479 * when the set of tokens that received the event changes. It is not logged again as long as the
3480 * user is interacting with the same windows.
3481 *
3482 * The second role is to track input device activity for metrics collection. For each input event,
3483 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3484 * input_interaction logs, the device interaction is reported even when the set of interaction
3485 * tokens do not change.
3486 *
3487 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3488 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003489 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003490void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3491 const std::vector<InputTarget>& targets) {
3492 int32_t deviceId;
3493 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003494 // Skip ACTION_UP events, and all events other than keys and motions
3495 if (entry.type == EventEntry::Type::KEY) {
3496 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3497 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3498 return;
3499 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003500 deviceId = keyEntry.deviceId;
3501 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003502 } else if (entry.type == EventEntry::Type::MOTION) {
3503 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3504 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003505 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3506 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003507 return;
3508 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003509 deviceId = motionEntry.deviceId;
3510 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003511 } else {
3512 return; // Not a key or a motion
3513 }
3514
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003515 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003516 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003517 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003518 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003519 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003520 continue; // Skip windows that receive ACTION_OUTSIDE
3521 }
3522
3523 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003524 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003525 if (connection == nullptr) {
3526 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003527 }
3528 newConnectionTokens.insert(std::move(token));
3529 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003530 if (target.windowHandle) {
3531 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3532 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003533 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003534
3535 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3536 REQUIRES(mLock) {
3537 scoped_unlock unlock(mLock);
3538 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3539 };
3540 postCommandLocked(std::move(command));
3541
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003542 if (newConnectionTokens == mInteractionConnectionTokens) {
3543 return; // no change
3544 }
3545 mInteractionConnectionTokens = newConnectionTokens;
3546
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003547 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003548 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003549 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003550 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003551 std::string message = "Interaction with: " + targetList;
3552 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003553 message += "<none>";
3554 }
3555 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3556}
3557
chaviwfd6d3512019-03-25 13:23:49 -07003558void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003559 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003560 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003561 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3562 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003563 return;
3564 }
3565
Vishnu Nairc519ff72021-01-21 08:23:08 -08003566 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003567 if (focusedToken == token) {
3568 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003569 return;
3570 }
3571
Prabir Pradhancef936d2021-07-21 16:17:52 +00003572 auto command = [this, token]() REQUIRES(mLock) {
3573 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003574 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003575 };
3576 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577}
3578
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003579status_t InputDispatcher::publishMotionEvent(Connection& connection,
3580 DispatchEntry& dispatchEntry) const {
3581 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3582 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3583
3584 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003585 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003586
3587 // Set the X and Y offset and X and Y scale depending on the input source.
3588 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003589 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003590 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3591 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003592 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003593 scaledCoords[i] = motionEntry.pointerCoords[i];
3594 // Don't apply window scale here since we don't want scale to affect raw
3595 // coordinates. The scale will be sent back to the client and applied
3596 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003597 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003598 }
3599 usingCoords = scaledCoords;
3600 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003601 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003602 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003603 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003604 scaledCoords[i].clear();
3605 }
3606 usingCoords = scaledCoords;
3607 }
3608
3609 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3610
3611 // Publish the motion event.
3612 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003613 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3614 motionEntry.source, motionEntry.displayId, std::move(hmac),
3615 motionEntry.action, motionEntry.actionButton,
3616 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3617 motionEntry.metaState, motionEntry.buttonState,
3618 motionEntry.classification, dispatchEntry.transform,
3619 motionEntry.xPrecision, motionEntry.yPrecision,
3620 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3621 dispatchEntry.rawTransform, motionEntry.downTime,
3622 motionEntry.eventTime, motionEntry.getPointerCount(),
3623 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003624}
3625
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003627 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003628 ATRACE_NAME_IF(ATRACE_ENABLED(),
3629 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3630 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003631 if (DEBUG_DISPATCH_CYCLE) {
3632 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003635 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003636 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003638 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003639 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640
3641 // Publish the event.
3642 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003643 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3644 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003645 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003646 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3647 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003648 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003649 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3650 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003653 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003654 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003655 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3656 keyEntry.deviceId, keyEntry.source,
3657 keyEntry.displayId, std::move(hmac),
3658 keyEntry.action, dispatchEntry->resolvedFlags,
3659 keyEntry.keyCode, keyEntry.scanCode,
3660 keyEntry.metaState, keyEntry.repeatCount,
3661 keyEntry.downTime, keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003662 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 }
3664
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003665 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003666 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003667 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3668 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003669 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003670 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003671 break;
3672 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003673
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003674 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003676 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003677 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003678 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003679 break;
3680 }
3681
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003682 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3683 const TouchModeEntry& touchModeEntry =
3684 static_cast<const TouchModeEntry&>(eventEntry);
3685 status = connection->inputPublisher
3686 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3687 touchModeEntry.inTouchMode);
3688
3689 break;
3690 }
3691
Prabir Pradhan99987712020-11-10 18:43:05 -08003692 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3693 const auto& captureEntry =
3694 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3695 status = connection->inputPublisher
3696 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003697 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003698 break;
3699 }
3700
arthurhungb89ccb02020-12-30 16:19:01 +08003701 case EventEntry::Type::DRAG: {
3702 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3703 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3704 dragEntry.id, dragEntry.x,
3705 dragEntry.y,
3706 dragEntry.isExiting);
3707 break;
3708 }
3709
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003710 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003711 case EventEntry::Type::DEVICE_RESET:
3712 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003713 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003714 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003715 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 }
3718
3719 // Check the result.
3720 if (status) {
3721 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003722 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 "This is unexpected because the wait queue is empty, so the pipe "
3725 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003726 "event to it, status=%s(%d)",
3727 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3728 status);
Harry Cutts33476232023-01-30 19:57:29 +00003729 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 } else {
3731 // Pipe is full and we are waiting for the app to finish process some events
3732 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003733 if (DEBUG_DISPATCH_CYCLE) {
3734 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3735 "waiting for the application to catch up",
3736 connection->getInputChannelName().c_str());
3737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 }
3739 } else {
3740 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003741 "status=%s(%d)",
3742 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3743 status);
Harry Cutts33476232023-01-30 19:57:29 +00003744 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 }
3746 return;
3747 }
3748
3749 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003750 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3751 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3752 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003753 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003754 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003755 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003756 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003757 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759}
3760
chaviw09c8d2d2020-08-24 15:48:26 -07003761std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3762 size_t size;
3763 switch (event.type) {
3764 case VerifiedInputEvent::Type::KEY: {
3765 size = sizeof(VerifiedKeyEvent);
3766 break;
3767 }
3768 case VerifiedInputEvent::Type::MOTION: {
3769 size = sizeof(VerifiedMotionEvent);
3770 break;
3771 }
3772 }
3773 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3774 return mHmacKeyManager.sign(start, size);
3775}
3776
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003777const std::array<uint8_t, 32> InputDispatcher::getSignature(
3778 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003779 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003780 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003781 // Only sign events up and down events as the purely move events
3782 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003783 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003784 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003785
3786 VerifiedMotionEvent verifiedEvent =
3787 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3788 verifiedEvent.actionMasked = actionMasked;
3789 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3790 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003791}
3792
3793const std::array<uint8_t, 32> InputDispatcher::getSignature(
3794 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3795 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3796 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003797 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003798}
3799
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003801 const std::shared_ptr<Connection>& connection,
3802 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003803 if (DEBUG_DISPATCH_CYCLE) {
3804 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3805 connection->getInputChannelName().c_str(), seq, toString(handled));
3806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003808 if (connection->status == Connection::Status::BROKEN ||
3809 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 return;
3811 }
3812
3813 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003814 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3815 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3816 };
3817 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818}
3819
3820void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003821 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003822 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003823 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003824 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3825 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827
3828 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003829 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003830 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003831 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003832 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833
3834 // The connection appears to be unrecoverably broken.
3835 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003836 if (connection->status == Connection::Status::NORMAL) {
3837 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
3839 if (notify) {
3840 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003841 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3842 connection->getInputChannelName().c_str());
3843
3844 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003845 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003846 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003847 };
3848 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 }
3850 }
3851}
3852
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003853void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003854 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003855 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003856 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 }
3858}
3859
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003860void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003862 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864}
3865
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003866int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3867 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003868 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003869 if (connection == nullptr) {
3870 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3871 connectionToken.get(), events);
3872 return 0; // remove the callback
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 bool notify;
3876 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3877 if (!(events & ALOOPER_EVENT_INPUT)) {
3878 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3879 "events=0x%x",
3880 connection->getInputChannelName().c_str(), events);
3881 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003884 nsecs_t currentTime = now();
3885 bool gotOne = false;
3886 status_t status = OK;
3887 for (;;) {
3888 Result<InputPublisher::ConsumerResponse> result =
3889 connection->inputPublisher.receiveConsumerResponse();
3890 if (!result.ok()) {
3891 status = result.error().code();
3892 break;
3893 }
3894
3895 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3896 const InputPublisher::Finished& finish =
3897 std::get<InputPublisher::Finished>(*result);
3898 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3899 finish.consumeTime);
3900 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003901 if (shouldReportMetricsForConnection(*connection)) {
3902 const InputPublisher::Timeline& timeline =
3903 std::get<InputPublisher::Timeline>(*result);
3904 mLatencyTracker
3905 .trackGraphicsLatency(timeline.inputEventId,
3906 connection->inputChannel->getConnectionToken(),
3907 std::move(timeline.graphicsTimeline));
3908 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003909 }
3910 gotOne = true;
3911 }
3912 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003913 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003914 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 return 1;
3916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003919 notify = status != DEAD_OBJECT || !connection->monitor;
3920 if (notify) {
3921 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3922 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3923 status);
3924 }
3925 } else {
3926 // Monitor channels are never explicitly unregistered.
3927 // We do it automatically when the remote endpoint is closed so don't warn about them.
3928 const bool stillHaveWindowHandle =
3929 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3930 notify = !connection->monitor && stillHaveWindowHandle;
3931 if (notify) {
3932 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3933 connection->getInputChannelName().c_str(), events);
3934 }
3935 }
3936
3937 // Remove the channel.
3938 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3939 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940}
3941
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003942void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003944 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003945 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 }
3947}
3948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003950 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003951 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003952 for (const Monitor& monitor : monitors) {
3953 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003954 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003955 }
3956}
3957
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003959 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003960 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003961 if (connection == nullptr) {
3962 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003964
3965 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966}
3967
3968void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003969 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003970 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 return;
3972 }
3973
3974 nsecs_t currentTime = now();
3975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003976 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003977 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003979 if (cancelationEvents.empty()) {
3980 return;
3981 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00003982
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003983 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3984 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003985 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003986 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003987 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003988 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003989
Arthur Hungb3307ee2021-10-14 10:57:37 +00003990 std::string reason = std::string("reason=").append(options.reason);
3991 android_log_event_list(LOGTAG_INPUT_CANCEL)
3992 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3993
hongzuo liu95785e22022-09-06 02:51:35 +00003994 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003995 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003996 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00003997 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003998
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003999 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004000 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004001 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004002
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004003 switch (cancelationEventEntry->type) {
4004 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004005 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004006 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4007 ? std::make_optional(keyEntry.displayId)
4008 : std::nullopt;
4009 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004010 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4011 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004012 } else {
4013 targets.emplace_back(fallbackTarget);
4014 }
4015 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004018 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004019 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004020 const std::optional<int32_t> targetDisplay =
4021 motionEntry.displayId != ADISPLAY_ID_NONE
4022 ? std::make_optional(motionEntry.displayId)
4023 : std::nullopt;
4024 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004025 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004026 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004027 pointerIndex++) {
4028 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4029 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004030 if (mDragState && mDragState->dragWindow->getToken() == token &&
4031 pointerIds.test(mDragState->pointerId)) {
4032 LOG(INFO) << __func__
4033 << ": Canceling drag and drop because the pointers for the drag "
4034 "window are being canceled.";
4035 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4036 mDragState.reset();
4037 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004038 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4039 ftl::Flags<InputTarget::Flags>(), pointerIds,
4040 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004041 } else {
4042 targets.emplace_back(fallbackTarget);
4043 const auto it = mDisplayInfos.find(motionEntry.displayId);
4044 if (it != mDisplayInfos.end()) {
4045 targets.back().displayTransform = it->second.transform;
4046 targets.back().setDefaultPointerTransform(it->second.transform);
4047 }
4048 }
4049 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004050 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004052 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004053 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004054 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4055 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004056 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004057 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004058 break;
4059 }
4060 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004061 case EventEntry::Type::DEVICE_RESET:
4062 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004063 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004064 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004065 break;
4066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 }
4068
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004069 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004070 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004072
hongzuo liu95785e22022-09-06 02:51:35 +00004073 // If the outbound queue was previously empty, start the dispatch cycle going.
4074 if (wasEmpty && !connection->outboundQueue.empty()) {
4075 startDispatchCycleLocked(currentTime, connection);
4076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077}
4078
Svet Ganov5d3bc372020-01-26 23:11:07 -08004079void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004080 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004081 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004082 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004083 return;
4084 }
4085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004086 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004087 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004088
4089 if (downEvents.empty()) {
4090 return;
4091 }
4092
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004094 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4095 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004096 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004097
chaviw98318de2021-05-19 16:45:23 -05004098 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004099 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004100
hongzuo liu95785e22022-09-06 02:51:35 +00004101 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004102 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004103 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004104 switch (downEventEntry->type) {
4105 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004106 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4107 if (windowHandle != nullptr) {
4108 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004109 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004110 pointerIndex++) {
4111 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4112 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004113 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4114 targetFlags, pointerIds, motionEntry.downTime,
4115 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004116 } else {
4117 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4118 .flags = targetFlags});
4119 const auto it = mDisplayInfos.find(motionEntry.displayId);
4120 if (it != mDisplayInfos.end()) {
4121 targets.back().displayTransform = it->second.transform;
4122 targets.back().setDefaultPointerTransform(it->second.transform);
4123 }
4124 }
4125 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004126 break;
4127 }
4128
4129 case EventEntry::Type::KEY:
4130 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004131 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004132 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004133 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004134 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004135 case EventEntry::Type::SENSOR:
4136 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004137 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004138 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004139 break;
4140 }
4141 }
4142
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004143 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004144 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004145 }
4146
hongzuo liu95785e22022-09-06 02:51:35 +00004147 // If the outbound queue was previously empty, start the dispatch cycle going.
4148 if (wasEmpty && !connection->outboundQueue.empty()) {
4149 startDispatchCycleLocked(downTime, connection);
4150 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004151}
4152
Arthur Hungc539dbb2022-12-08 07:45:36 +00004153void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4154 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4155 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004156 std::shared_ptr<Connection> wallpaperConnection =
4157 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004158 if (wallpaperConnection != nullptr) {
4159 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4160 }
4161 }
4162}
4163
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004164std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004165 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4166 nsecs_t splitDownTime) {
4167 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
4169 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004170 std::vector<PointerProperties> splitPointerProperties;
4171 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004173 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 uint32_t splitPointerCount = 0;
4175
4176 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004177 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004179 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004181 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004183 splitPointerProperties.push_back(pointerProperties);
4184 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 splitPointerCount += 1;
4186 }
4187 }
4188
4189 if (splitPointerCount != pointerIds.count()) {
4190 // This is bad. We are missing some of the pointers that we expected to deliver.
4191 // Most likely this indicates that we received an ACTION_MOVE events that has
4192 // different pointer ids than we expected based on the previous ACTION_DOWN
4193 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4194 // in this way.
4195 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004196 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004197 "a broken sequence of pointer ids from the input device: %s",
4198 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004199 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 }
4201
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004202 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4205 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004206 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004208 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004210 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 if (pointerIds.count() == 1) {
4212 // The first/last pointer went down/up.
4213 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004214 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004215 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4216 ? AMOTION_EVENT_ACTION_CANCEL
4217 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 } else {
4219 // A secondary pointer went down/up.
4220 uint32_t splitPointerIndex = 0;
4221 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4222 splitPointerIndex += 1;
4223 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 action = maskedAction |
4225 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
4227 } else {
4228 // An unrelated pointer changed.
4229 action = AMOTION_EVENT_ACTION_MOVE;
4230 }
4231 }
4232
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004233 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4234 logDispatchStateLocked();
4235 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4236 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4237 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004238 }
4239
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004240 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004241 ATRACE_NAME_IF(ATRACE_ENABLED(),
4242 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4243 ").",
4244 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004246 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4247 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004248 originalMotionEntry.deviceId, originalMotionEntry.source,
4249 originalMotionEntry.displayId,
4250 originalMotionEntry.policyFlags, action,
4251 originalMotionEntry.actionButton,
4252 originalMotionEntry.flags, originalMotionEntry.metaState,
4253 originalMotionEntry.buttonState,
4254 originalMotionEntry.classification,
4255 originalMotionEntry.edgeFlags,
4256 originalMotionEntry.xPrecision,
4257 originalMotionEntry.yPrecision,
4258 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004259 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004260 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 return splitMotionEntry;
4263}
4264
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004265void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4266 std::scoped_lock _l(mLock);
4267 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4268}
4269
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004270void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004271 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004272 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
Antonio Kantekf16f2832021-09-28 04:39:20 +00004275 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004277 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004280 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 } // release lock
4283
4284 if (needWake) {
4285 mLooper->wake();
4286 }
4287}
4288
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004289void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004290 ALOGD_IF(debugInboundEventDetails(),
4291 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4292 ", deviceId=%d, source=%s, displayId=%" PRId32
4293 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4294 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004295 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4296 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4297 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004298 Result<void> keyCheck = validateKeyEvent(args.action);
4299 if (!keyCheck.ok()) {
4300 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 return;
4302 }
4303
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004304 uint32_t policyFlags = args.policyFlags;
4305 int32_t flags = args.flags;
4306 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004307 // InputDispatcher tracks and generates key repeats on behalf of
4308 // whatever notifies it, so repeatCount should always be set to 0
4309 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4311 policyFlags |= POLICY_FLAG_VIRTUAL;
4312 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 if (policyFlags & POLICY_FLAG_FUNCTION) {
4315 metaState |= AMETA_FUNCTION_ON;
4316 }
4317
4318 policyFlags |= POLICY_FLAG_TRUSTED;
4319
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004320 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004322 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4323 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4324 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
Michael Wright2b3c3302018-03-02 17:19:13 +00004326 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004327 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004328 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4329 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004330 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Antonio Kantekf16f2832021-09-28 04:39:20 +00004333 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 { // acquire lock
4335 mLock.lock();
4336
4337 if (shouldSendKeyToInputFilterLocked(args)) {
4338 mLock.unlock();
4339
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004340 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004341 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 return; // event was consumed by the filter
4343 }
4344
4345 mLock.lock();
4346 }
4347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004349 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4350 args.deviceId, args.source, args.displayId, policyFlags,
4351 args.action, flags, keyCode, args.scanCode, metaState,
4352 repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004354 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 mLock.unlock();
4356 } // release lock
4357
4358 if (needWake) {
4359 mLooper->wake();
4360 }
4361}
4362
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004363bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 return mInputFilterEnabled;
4365}
4366
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004367void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004368 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004369 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004370 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004371 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004372 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4373 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004374 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4375 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4376 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4377 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4378 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004379 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004380 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4381 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004382 i, args.pointerProperties[i].id,
4383 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4384 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4385 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4386 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4387 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4388 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4389 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4390 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4391 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4392 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004395
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004396 Result<void> motionCheck =
4397 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4398 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004399 if (!motionCheck.ok()) {
4400 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4401 return;
4402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004404 if (DEBUG_VERIFY_EVENTS) {
4405 auto [it, _] =
4406 mVerifiersByDisplay.try_emplace(args.displayId,
4407 StringPrintf("display %" PRId32, args.displayId));
4408 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004409 it->second.processMovement(args.deviceId, args.source, args.action,
4410 args.getPointerCount(), args.pointerProperties.data(),
4411 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004412 if (!result.ok()) {
4413 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4414 }
4415 }
4416
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004417 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004419
4420 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004421 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004422 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4423 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426
Antonio Kantekf16f2832021-09-28 04:39:20 +00004427 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 { // acquire lock
4429 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004430 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4431 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4432 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004433 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004434 if (touchStateIt != mTouchStatesByDisplay.end()) {
4435 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004436 if (touchState.hasTouchingPointers(args.deviceId) ||
4437 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004438 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4439 }
4440 }
4441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442
4443 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004444 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004445 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004446 displayTransform = it->second.transform;
4447 }
4448
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 mLock.unlock();
4450
4451 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004452 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4453 args.action, args.actionButton, args.flags, args.edgeFlags,
4454 args.metaState, args.buttonState, args.classification,
4455 displayTransform, args.xPrecision, args.yPrecision,
4456 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004457 args.downTime, args.eventTime, args.getPointerCount(),
4458 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459
4460 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004461 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 return; // event was consumed by the filter
4463 }
4464
4465 mLock.lock();
4466 }
4467
4468 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004469 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004470 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4471 args.deviceId, args.source, args.displayId,
4472 policyFlags, args.action, args.actionButton,
4473 args.flags, args.metaState, args.buttonState,
4474 args.classification, args.edgeFlags, args.xPrecision,
4475 args.yPrecision, args.xCursorPosition,
4476 args.yCursorPosition, args.downTime,
4477 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004479 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4480 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004481 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004482 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004483 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4484 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4485 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004486 }
4487
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004488 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 mLock.unlock();
4490 } // release lock
4491
4492 if (needWake) {
4493 mLooper->wake();
4494 }
4495}
4496
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004498 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004499 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4500 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004501 args.id, args.eventTime, args.deviceId, args.source,
4502 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004503 }
Chris Yef59a2f42020-10-16 12:55:26 -07004504
Antonio Kantekf16f2832021-09-28 04:39:20 +00004505 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004506 { // acquire lock
4507 mLock.lock();
4508
4509 // Just enqueue a new sensor event.
4510 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004511 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4512 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4513 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004514
4515 needWake = enqueueInboundEventLocked(std::move(newEntry));
4516 mLock.unlock();
4517 } // release lock
4518
4519 if (needWake) {
4520 mLooper->wake();
4521 }
4522}
4523
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004524void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004525 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004526 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4527 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004528 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004529 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004530}
4531
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004532bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004533 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534}
4535
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004536void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004537 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004538 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4539 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004540 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004543 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004545 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546}
4547
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004548void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004549 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004550 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4551 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Antonio Kantekf16f2832021-09-28 04:39:20 +00004554 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004556 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004558 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004559 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004560 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004561
4562 for (auto& [_, verifier] : mVerifiersByDisplay) {
4563 verifier.resetDevice(args.deviceId);
4564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 } // release lock
4566
4567 if (needWake) {
4568 mLooper->wake();
4569 }
4570}
4571
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004572void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004573 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004574 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4575 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004576 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004577
Antonio Kantekf16f2832021-09-28 04:39:20 +00004578 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004579 { // acquire lock
4580 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004581 auto entry =
4582 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004583 needWake = enqueueInboundEventLocked(std::move(entry));
4584 } // release lock
4585
4586 if (needWake) {
4587 mLooper->wake();
4588 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004589}
4590
Prabir Pradhan5735a322022-04-11 17:23:34 +00004591InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004592 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004593 InputEventInjectionSync syncMode,
4594 std::chrono::milliseconds timeout,
4595 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004596 Result<void> eventValidation = validateInputEvent(*event);
4597 if (!eventValidation.ok()) {
4598 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4599 return InputEventInjectionResult::FAILED;
4600 }
4601
Prabir Pradhan65613802023-02-22 23:36:58 +00004602 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004603 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4604 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4605 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4606 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004607 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004608 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609
Prabir Pradhan5735a322022-04-11 17:23:34 +00004610 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004612 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004613 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4614 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4615 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4616 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4617 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004618 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004619 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004620 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004621 }
4622
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004623 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4624 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4625
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004626 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004628 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004629 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004630 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004631 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004632 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4633 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4634 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004635 int32_t keyCode = incomingKey.getKeyCode();
4636 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004637 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004638 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004639 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4640 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4641 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004643 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4644 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004645 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004646
4647 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4648 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004649 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4651 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4652 std::to_string(t.duration().count()).c_str());
4653 }
4654 }
4655
4656 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004657 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004658 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4659 incomingKey.getEventTime(), resolvedDeviceId,
4660 incomingKey.getSource(), incomingKey.getDisplayId(),
4661 policyFlags, action, flags, keyCode,
4662 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004663 incomingKey.getRepeatCount(),
4664 incomingKey.getDownTime());
4665 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004666 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 }
4668
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004669 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004670 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004671 const bool isPointerEvent =
4672 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4673 // If a pointer event has no displayId specified, inject it to the default display.
4674 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4675 ? ADISPLAY_ID_DEFAULT
4676 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004677 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004678
4679 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004680 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004681 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004682 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004683 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4684 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4685 std::to_string(t.duration().count()).c_str());
4686 }
4687 }
4688
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004689 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4690 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4691 }
4692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004693 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004694 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004695 const size_t pointerCount = motionEvent.getPointerCount();
4696 const std::vector<PointerProperties>
4697 pointerProperties(motionEvent.getPointerProperties(),
4698 motionEvent.getPointerProperties() + pointerCount);
4699
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004700 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004701 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004702 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4703 *sampleEventTimes, resolvedDeviceId,
4704 motionEvent.getSource(), displayId, policyFlags,
4705 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004706 motionEvent.getActionButton(), flags,
4707 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004708 motionEvent.getButtonState(),
4709 motionEvent.getClassification(),
4710 motionEvent.getEdgeFlags(),
4711 motionEvent.getXPrecision(),
4712 motionEvent.getYPrecision(),
4713 motionEvent.getRawXCursorPosition(),
4714 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004715 motionEvent.getDownTime(), pointerProperties,
4716 std::vector<PointerCoords>(samplePointerCoords,
4717 samplePointerCoords +
4718 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004719 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004720 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004721 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004723 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004724 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004725 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4726 resolvedDeviceId, motionEvent.getSource(), displayId,
4727 policyFlags, motionEvent.getAction(),
4728 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004729 motionEvent.getMetaState(), motionEvent.getButtonState(),
4730 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4731 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4732 motionEvent.getRawXCursorPosition(),
4733 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4734 pointerProperties,
4735 std::vector<PointerCoords>(samplePointerCoords,
4736 samplePointerCoords +
4737 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004738 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4739 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004740 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741 }
4742 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004746 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004747 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 }
4749
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004751 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004752 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004753 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004754 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004755 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004756 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 }
4758
4759 mLock.unlock();
4760
4761 if (needWake) {
4762 mLooper->wake();
4763 }
4764
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004765 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004767 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004769 if (syncMode == InputEventInjectionSync::NONE) {
4770 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 } else {
4772 for (;;) {
4773 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004774 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 break;
4776 }
4777
4778 nsecs_t remainingTimeout = endTime - now();
4779 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004780 if (DEBUG_INJECTION) {
4781 ALOGD("injectInputEvent - Timed out waiting for injection result "
4782 "to become available.");
4783 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004784 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 break;
4786 }
4787
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004788 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 }
4790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4792 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004794 if (DEBUG_INJECTION) {
4795 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4796 injectionState->pendingForegroundDispatches);
4797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 nsecs_t remainingTimeout = endTime - now();
4799 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004800 if (DEBUG_INJECTION) {
4801 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4802 "dispatches to finish.");
4803 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004804 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 break;
4806 }
4807
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004808 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 }
4810 }
4811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 } // release lock
4813
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004814 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004815 LOG(INFO) << "injectInputEvent - Finished with result "
4816 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818
4819 return injectionResult;
4820}
4821
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004822std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004823 std::array<uint8_t, 32> calculatedHmac;
4824 std::unique_ptr<VerifiedInputEvent> result;
4825 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004826 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004827 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4828 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4829 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004830 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004831 break;
4832 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004833 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004834 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4835 VerifiedMotionEvent verifiedMotionEvent =
4836 verifiedMotionEventFromMotionEvent(motionEvent);
4837 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004838 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004839 break;
4840 }
4841 default: {
4842 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4843 return nullptr;
4844 }
4845 }
4846 if (calculatedHmac == INVALID_HMAC) {
4847 return nullptr;
4848 }
tyiu1573a672023-02-21 22:38:32 +00004849 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004850 return nullptr;
4851 }
4852 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004853}
4854
Prabir Pradhan24047542023-11-02 17:14:59 +00004855void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004856 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004857 if (!entry.injectionState) {
4858 // Not an injected event.
4859 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004861
4862 InjectionState& injectionState = *entry.injectionState;
4863 if (DEBUG_INJECTION) {
4864 LOG(INFO) << "Setting input event injection result to "
4865 << ftl::enum_string(injectionResult);
4866 }
4867
4868 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4869 // Log the outcome since the injector did not wait for the injection result.
4870 switch (injectionResult) {
4871 case InputEventInjectionResult::SUCCEEDED:
4872 ALOGV("Asynchronous input event injection succeeded.");
4873 break;
4874 case InputEventInjectionResult::TARGET_MISMATCH:
4875 ALOGV("Asynchronous input event injection target mismatch.");
4876 break;
4877 case InputEventInjectionResult::FAILED:
4878 ALOGW("Asynchronous input event injection failed.");
4879 break;
4880 case InputEventInjectionResult::TIMED_OUT:
4881 ALOGW("Asynchronous input event injection timed out.");
4882 break;
4883 case InputEventInjectionResult::PENDING:
4884 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4885 break;
4886 }
4887 }
4888
4889 injectionState.injectionResult = injectionResult;
4890 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891}
4892
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004893void InputDispatcher::transformMotionEntryForInjectionLocked(
4894 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004895 // Input injection works in the logical display coordinate space, but the input pipeline works
4896 // display space, so we need to transform the injected events accordingly.
4897 const auto it = mDisplayInfos.find(entry.displayId);
4898 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004899 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004900
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004901 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4902 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4903 const vec2 cursor =
4904 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4905 {entry.xCursorPosition, entry.yCursorPosition});
4906 entry.xCursorPosition = cursor.x;
4907 entry.yCursorPosition = cursor.y;
4908 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004909 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004910 entry.pointerCoords[i] =
4911 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4912 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004913 }
4914}
4915
Prabir Pradhan24047542023-11-02 17:14:59 +00004916void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004917 if (entry.injectionState) {
4918 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 }
4920}
4921
Prabir Pradhan24047542023-11-02 17:14:59 +00004922void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004923 if (entry.injectionState) {
4924 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004926 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004927 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929 }
4930}
4931
chaviw98318de2021-05-19 16:45:23 -05004932const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004933 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004934 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004935 auto it = mWindowHandlesByDisplay.find(displayId);
4936 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004937}
4938
chaviw98318de2021-05-19 16:45:23 -05004939sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004940 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004941 if (windowHandleToken == nullptr) {
4942 return nullptr;
4943 }
4944
Prabir Pradhan16463382023-10-12 23:03:19 +00004945 if (!displayId) {
4946 // Look through all displays.
4947 for (auto& it : mWindowHandlesByDisplay) {
4948 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4949 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4950 if (windowHandle->getToken() == windowHandleToken) {
4951 return windowHandle;
4952 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004955 return nullptr;
4956 }
4957
Prabir Pradhan16463382023-10-12 23:03:19 +00004958 // Only look through the requested display.
4959 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004960 if (windowHandle->getToken() == windowHandleToken) {
4961 return windowHandle;
4962 }
4963 }
4964 return nullptr;
4965}
4966
chaviw98318de2021-05-19 16:45:23 -05004967sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4968 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004969 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004970 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4971 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004972 if (handle->getId() == windowHandle->getId() &&
4973 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004974 if (windowHandle->getInfo()->displayId != it.first) {
4975 ALOGE("Found window %s in display %" PRId32
4976 ", but it should belong to display %" PRId32,
4977 windowHandle->getName().c_str(), it.first,
4978 windowHandle->getInfo()->displayId);
4979 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004980 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 }
4983 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004984 return nullptr;
4985}
4986
chaviw98318de2021-05-19 16:45:23 -05004987sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004988 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4989 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990}
4991
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004992ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4993 auto displayInfoIt = mDisplayInfos.find(displayId);
4994 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4995 : kIdentityTransform;
4996}
4997
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004998bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4999 const MotionEntry& motionEntry) const {
5000 const WindowInfo& info = *window->getInfo();
5001
5002 // Skip spy window targets that are not valid for targeted injection.
5003 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005004 return false;
5005 }
5006
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005007 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5008 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5009 return false;
5010 }
5011
5012 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5013 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5014 window->getName().c_str());
5015 return false;
5016 }
5017
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005018 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005019 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005020 ALOGW("Not sending touch to %s because there's no corresponding connection",
5021 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005022 return false;
5023 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005024
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005025 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005026 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005027 return false;
5028 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005029
5030 // Drop events that can't be trusted due to occlusion
5031 const auto [x, y] = resolveTouchedPosition(motionEntry);
5032 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5033 if (!isTouchTrustedLocked(occlusionInfo)) {
5034 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005035 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005036 for (const auto& log : occlusionInfo.debugInfo) {
5037 ALOGD("%s", log.c_str());
5038 }
5039 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005040 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5041 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005042 return false;
5043 }
5044
5045 // Drop touch events if requested by input feature
5046 if (shouldDropInput(motionEntry, window)) {
5047 return false;
5048 }
5049
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005050 return true;
5051}
5052
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005053std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5054 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005055 auto connectionIt = mConnectionsByToken.find(token);
5056 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005057 return nullptr;
5058 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005059 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005060}
5061
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005062void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005063 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5064 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005065 // Remove all handles on a display if there are no windows left.
5066 mWindowHandlesByDisplay.erase(displayId);
5067 return;
5068 }
5069
5070 // Since we compare the pointer of input window handles across window updates, we need
5071 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005072 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5073 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5074 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005075 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005076 }
5077
chaviw98318de2021-05-19 16:45:23 -05005078 std::vector<sp<WindowInfoHandle>> newHandles;
5079 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005080 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005081 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005082 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005083 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005084 const bool canReceiveInput =
5085 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5086 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005087 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005088 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005089 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005090 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005091 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005092 }
5093
5094 if (info->displayId != displayId) {
5095 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5096 handle->getName().c_str(), displayId, info->displayId);
5097 continue;
5098 }
5099
Robert Carredd13602020-04-13 17:24:34 -07005100 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5101 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005102 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005103 oldHandle->updateFrom(handle);
5104 newHandles.push_back(oldHandle);
5105 } else {
5106 newHandles.push_back(handle);
5107 }
5108 }
5109
5110 // Insert or replace
5111 mWindowHandlesByDisplay[displayId] = newHandles;
5112}
5113
Arthur Hungb92218b2018-08-14 12:00:21 +08005114/**
5115 * Called from InputManagerService, update window handle list by displayId that can receive input.
5116 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5117 * If set an empty list, remove all handles from the specific display.
5118 * For focused handle, check if need to change and send a cancel event to previous one.
5119 * For removed handle, check if need to send a cancel event if already in touch.
5120 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005121void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005122 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005123 if (DEBUG_FOCUS) {
5124 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005125 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005126 windowList += iwh->getName() + " ";
5127 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005128 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
Prabir Pradhand65552b2021-10-07 11:23:50 -07005131 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005132 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005133 const WindowInfo& info = *window->getInfo();
5134
5135 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005136 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005137 if (noInputWindow && window->getToken() != nullptr) {
5138 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5139 window->getName().c_str());
5140 window->releaseChannel();
5141 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005142
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005143 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005144 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5145 !info.inputConfig.test(
5146 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005147 "%s has feature SPY, but is not a trusted overlay.",
5148 window->getName().c_str());
5149
Prabir Pradhand65552b2021-10-07 11:23:50 -07005150 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005151 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5152 !info.inputConfig.test(
5153 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005154 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5155 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005156 }
5157
Arthur Hung72d8dc32020-03-28 00:48:39 +00005158 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005159 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160
chaviw98318de2021-05-19 16:45:23 -05005161 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005162
chaviw98318de2021-05-19 16:45:23 -05005163 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005164
Vishnu Nairc519ff72021-01-21 08:23:08 -08005165 std::optional<FocusResolver::FocusChanges> changes =
5166 mFocusResolver.setInputWindows(displayId, windowHandles);
5167 if (changes) {
5168 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005171 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5172 mTouchStatesByDisplay.find(displayId);
5173 if (stateIt != mTouchStatesByDisplay.end()) {
5174 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005175 for (size_t i = 0; i < state.windows.size();) {
5176 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005177 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005178 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5179 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005180 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005181 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5182 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005183 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005184 "touched window was removed");
5185 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005186 // Since we are about to drop the touch, cancel the events for the wallpaper as
5187 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005188 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005189 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5190 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005191 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005192 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005195 state.windows.erase(state.windows.begin() + i);
5196 } else {
5197 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 }
5199 }
arthurhungb89ccb02020-12-30 16:19:01 +08005200
arthurhung6d4bed92021-03-17 11:59:33 +08005201 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005202 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005203 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005204 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005205 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005206 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5207 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005208 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005209 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005210 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005211
Arthur Hung72d8dc32020-03-28 00:48:39 +00005212 // Release information for windows that are no longer present.
5213 // This ensures that unused input channels are released promptly.
5214 // Otherwise, they might stick around until the window handle is destroyed
5215 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005216 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005217 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005218 if (DEBUG_FOCUS) {
5219 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005220 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005221 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005222 }
chaviw291d88a2019-02-14 10:33:58 -08005223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224}
5225
5226void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005227 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005228 if (DEBUG_FOCUS) {
5229 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5230 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5231 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005232 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005233 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005234 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 } // release lock
5236
5237 // Wake up poll loop since it may need to make new input dispatching choices.
5238 mLooper->wake();
5239}
5240
Vishnu Nair599f1412021-06-21 10:39:58 -07005241void InputDispatcher::setFocusedApplicationLocked(
5242 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5243 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5244 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5245
5246 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5247 return; // This application is already focused. No need to wake up or change anything.
5248 }
5249
5250 // Set the new application handle.
5251 if (inputApplicationHandle != nullptr) {
5252 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5253 } else {
5254 mFocusedApplicationHandlesByDisplay.erase(displayId);
5255 }
5256
5257 // No matter what the old focused application was, stop waiting on it because it is
5258 // no longer focused.
5259 resetNoFocusedWindowTimeoutLocked();
5260}
5261
Tiger Huang721e26f2018-07-24 22:26:19 +08005262/**
5263 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5264 * the display not specified.
5265 *
5266 * We track any unreleased events for each window. If a window loses the ability to receive the
5267 * released event, we will send a cancel event to it. So when the focused display is changed, we
5268 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5269 * display. The display-specified events won't be affected.
5270 */
5271void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005272 if (DEBUG_FOCUS) {
5273 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5274 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005275 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005276 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005277
5278 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005279 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005280 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005281 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005282 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005283 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005284 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005285 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005286 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005287 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005288 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005289 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5290 }
5291 }
5292 mFocusedDisplayId = displayId;
5293
Chris Ye3c2d6f52020-08-09 10:39:48 -07005294 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005295 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005296 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005297
Vishnu Nairad321cd2020-08-20 16:40:21 -07005298 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005299 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005300 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005301 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005302 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005303 }
5304 }
5305 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005306 } // release lock
5307
5308 // Wake up poll loop since it may need to make new input dispatching choices.
5309 mLooper->wake();
5310}
5311
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005313 if (DEBUG_FOCUS) {
5314 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
5317 bool changed;
5318 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005319 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320
5321 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5322 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005323 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325
5326 if (mDispatchEnabled && !enabled) {
5327 resetAndDropEverythingLocked("dispatcher is being disabled");
5328 }
5329
5330 mDispatchEnabled = enabled;
5331 mDispatchFrozen = frozen;
5332 changed = true;
5333 } else {
5334 changed = false;
5335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 } // release lock
5337
5338 if (changed) {
5339 // Wake up poll loop since it may need to make new input dispatching choices.
5340 mLooper->wake();
5341 }
5342}
5343
5344void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005345 if (DEBUG_FOCUS) {
5346 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348
5349 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005350 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
5352 if (mInputFilterEnabled == enabled) {
5353 return;
5354 }
5355
5356 mInputFilterEnabled = enabled;
5357 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5358 } // release lock
5359
5360 // Wake up poll loop since there might be work to do to drop everything.
5361 mLooper->wake();
5362}
5363
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005364bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005365 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005366 bool needWake = false;
5367 {
5368 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005369 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005370 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005371 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005372 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5373 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005374 mTouchModePerDisplay.count(displayId) == 0
5375 ? "not set"
5376 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5377
Antonio Kantek15beb512022-06-13 22:35:41 +00005378 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5379 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005380 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005381 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005382 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005383 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5384 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005385 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005386 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005387 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005388 return false;
5389 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005390 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005391 mTouchModePerDisplay[displayId] = inTouchMode;
5392 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5393 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005394 needWake = enqueueInboundEventLocked(std::move(entry));
5395 } // release lock
5396
5397 if (needWake) {
5398 mLooper->wake();
5399 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005400 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005401}
5402
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005403bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005404 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5405 if (focusedToken == nullptr) {
5406 return false;
5407 }
5408 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5409 return isWindowOwnedBy(windowHandle, pid, uid);
5410}
5411
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005412bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005413 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5414 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5415 const sp<WindowInfoHandle> windowHandle =
5416 getWindowHandleLocked(connectionToken);
5417 return isWindowOwnedBy(windowHandle, pid, uid);
5418 }) != mInteractionConnectionTokens.end();
5419}
5420
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005421void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5422 if (opacity < 0 || opacity > 1) {
5423 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5424 return;
5425 }
5426
5427 std::scoped_lock lock(mLock);
5428 mMaximumObscuringOpacityForTouch = opacity;
5429}
5430
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005431std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5432InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005433 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5434 for (TouchedWindow& w : state.windows) {
5435 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005436 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005437 }
5438 }
5439 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005440 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005441}
5442
arthurhungb89ccb02020-12-30 16:19:01 +08005443bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5444 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005445 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005446 if (DEBUG_FOCUS) {
5447 ALOGD("Trivial transfer to same window.");
5448 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005449 return true;
5450 }
5451
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005453 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454
Arthur Hungabbb9d82021-09-01 14:52:30 +00005455 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005456 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005457
Arthur Hungabbb9d82021-09-01 14:52:30 +00005458 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005459 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 return false;
5461 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005462 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5463 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005464 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5465 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005466 return false;
5467 }
5468 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005469
Arthur Hungabbb9d82021-09-01 14:52:30 +00005470 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5471 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005472 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005473 return false;
5474 }
5475
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005476 if (DEBUG_FOCUS) {
5477 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005478 touchedWindow->windowHandle->getName().c_str(),
5479 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 }
5481
Arthur Hungabbb9d82021-09-01 14:52:30 +00005482 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005483 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005484 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005485 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005486 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487
Arthur Hungabbb9d82021-09-01 14:52:30 +00005488 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005489 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005490 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005491 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005492 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005493 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005494 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005495 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
5496 deviceId, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497
Arthur Hungabbb9d82021-09-01 14:52:30 +00005498 // Store the dragging window.
5499 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005500 if (pointerIds.count() != 1) {
5501 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5502 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005503 return false;
5504 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005505 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005506 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005507 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 }
5509
Arthur Hungabbb9d82021-09-01 14:52:30 +00005510 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005511 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5512 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005513 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005514 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005515 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5516 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005518 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5519 newTargetFlags);
5520
5521 // Check if the wallpaper window should deliver the corresponding event.
5522 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005523 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 } // release lock
5526
5527 // Wake up poll loop since it may need to make new input dispatching choices.
5528 mLooper->wake();
5529 return true;
5530}
5531
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005532/**
5533 * Get the touched foreground window on the given display.
5534 * Return null if there are no windows touched on that display, or if more than one foreground
5535 * window is being touched.
5536 */
5537sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5538 auto stateIt = mTouchStatesByDisplay.find(displayId);
5539 if (stateIt == mTouchStatesByDisplay.end()) {
5540 ALOGI("No touch state on display %" PRId32, displayId);
5541 return nullptr;
5542 }
5543
5544 const TouchState& state = stateIt->second;
5545 sp<WindowInfoHandle> touchedForegroundWindow;
5546 // If multiple foreground windows are touched, return nullptr
5547 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005548 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005549 if (touchedForegroundWindow != nullptr) {
5550 ALOGI("Two or more foreground windows: %s and %s",
5551 touchedForegroundWindow->getName().c_str(),
5552 window.windowHandle->getName().c_str());
5553 return nullptr;
5554 }
5555 touchedForegroundWindow = window.windowHandle;
5556 }
5557 }
5558 return touchedForegroundWindow;
5559}
5560
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005561// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005562bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005563 sp<IBinder> fromToken;
5564 { // acquire lock
5565 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005566 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005567 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005568 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5569 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005570 return false;
5571 }
5572
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005573 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5574 if (from == nullptr) {
5575 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5576 return false;
5577 }
5578
5579 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005580 } // release lock
5581
5582 return transferTouchFocus(fromToken, destChannelToken);
5583}
5584
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005586 if (DEBUG_FOCUS) {
5587 ALOGD("Resetting and dropping all events (%s).", reason);
5588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589
Michael Wrightfb04fd52022-11-24 22:31:11 +00005590 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 synthesizeCancelationEventsForAllConnectionsLocked(options);
5592
5593 resetKeyRepeatLocked();
5594 releasePendingEventLocked();
5595 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005596 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005598 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005599 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600}
5601
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005602void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005603 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 dumpDispatchStateLocked(dump);
5605
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005606 std::istringstream stream(dump);
5607 std::string line;
5608
5609 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005610 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 }
5612}
5613
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005614std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005615 std::string dump;
5616
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005617 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5618 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005619
5620 std::string windowName = "None";
5621 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005622 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005623 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5624 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5625 : "token has capture without window";
5626 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005627 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005628
5629 return dump;
5630}
5631
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005632void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005633 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5634 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5635 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005636 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637
Tiger Huang721e26f2018-07-24 22:26:19 +08005638 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5639 dump += StringPrintf(INDENT "FocusedApplications:\n");
5640 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5641 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005642 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005643 const std::chrono::duration timeout =
5644 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005645 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005646 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005647 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005650 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005652
Vishnu Nairc519ff72021-01-21 08:23:08 -08005653 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005654 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005656 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005657 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005658 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005659 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5660 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661 }
5662 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005663 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 }
5665
arthurhung6d4bed92021-03-17 11:59:33 +08005666 if (mDragState) {
5667 dump += StringPrintf(INDENT "DragState:\n");
5668 mDragState->dump(dump, INDENT2);
5669 }
5670
Arthur Hungb92218b2018-08-14 12:00:21 +08005671 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005672 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5673 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5674 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5675 const auto& displayInfo = it->second;
5676 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5677 displayInfo.logicalHeight);
5678 displayInfo.transform.dump(dump, "transform", INDENT4);
5679 } else {
5680 dump += INDENT2 "No DisplayInfo found!\n";
5681 }
5682
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005683 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005684 dump += INDENT2 "Windows:\n";
5685 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005686 dump += StringPrintf(INDENT3 "%zu: %s", i,
5687 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005688 }
5689 } else {
5690 dump += INDENT2 "Windows: <none>\n";
5691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 }
5693 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005694 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 if (!mGlobalMonitorsByDisplay.empty()) {
5698 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5699 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005700 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005703 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 }
5705
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005706 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707
5708 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005709 if (!mRecentQueue.empty()) {
5710 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005711 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005712 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005713 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005714 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719
5720 // Dump event currently being dispatched.
5721 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 dump += INDENT "PendingEvent:\n";
5723 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005724 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005725 dump += StringPrintf(", age=%" PRId64 "ms\n",
5726 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005728 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
5730
5731 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005732 if (!mInboundQueue.empty()) {
5733 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005734 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005735 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005736 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005737 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
Prabir Pradhancef936d2021-07-21 16:17:52 +00005743 if (!mCommandQueue.empty()) {
5744 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5745 } else {
5746 dump += INDENT "CommandQueue: <empty>\n";
5747 }
5748
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005749 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005750 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005751 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005752 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005754 connection->inputChannel->getFd().get(),
5755 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005756 connection->getWindowName().c_str(),
5757 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005758 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005760 if (!connection->outboundQueue.empty()) {
5761 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5762 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005763 dump += dumpQueue(connection->outboundQueue, currentTime);
5764
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005766 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 }
5768
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005769 if (!connection->waitQueue.empty()) {
5770 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5771 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005772 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005774 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005776 std::string inputStateDump = streamableToString(connection->inputState);
5777 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005778 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005779 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 }
5782 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005783 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 }
5785
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005786 dump += "input_flags::remove_app_switch_drops() = ";
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07005787 dump += toString(REMOVE_APP_SWITCH_DROPS);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005788 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005790 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5791 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005793 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 }
5795
Antonio Kantek15beb512022-06-13 22:35:41 +00005796 if (!mTouchModePerDisplay.empty()) {
5797 dump += INDENT "TouchModePerDisplay:\n";
5798 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5799 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5800 std::to_string(touchMode).c_str());
5801 }
5802 } else {
5803 dump += INDENT "TouchModePerDisplay: <none>\n";
5804 }
5805
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005806 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005807 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5808 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5809 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005810 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005811 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812}
5813
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005814void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005815 const size_t numMonitors = monitors.size();
5816 for (size_t i = 0; i < numMonitors; i++) {
5817 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005818 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005819 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5820 dump += "\n";
5821 }
5822}
5823
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005824class LooperEventCallback : public LooperCallback {
5825public:
5826 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5827 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5828
5829private:
5830 std::function<int(int events)> mCallback;
5831};
5832
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005833Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005834 if (DEBUG_CHANNEL_CREATION) {
5835 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005838 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005839 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005840 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005841
5842 if (result) {
5843 return base::Error(result) << "Failed to open input channel pair with name " << name;
5844 }
5845
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005847 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005849 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005850 std::shared_ptr<Connection> connection =
5851 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5852 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005854 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5855 ALOGE("Created a new connection, but the token %p is already known", token.get());
5856 }
5857 mConnectionsByToken.emplace(token, connection);
5858
5859 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5860 this, std::placeholders::_1, token);
5861
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005862 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005863 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 } // release lock
5865
5866 // Wake the looper because some connections have changed.
5867 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005868 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869}
5870
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005871Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005872 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005873 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005874 std::shared_ptr<InputChannel> serverChannel;
5875 std::unique_ptr<InputChannel> clientChannel;
5876 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5877 if (result) {
5878 return base::Error(result) << "Failed to open input channel pair with name " << name;
5879 }
5880
Michael Wright3dd60e22019-03-27 22:06:44 +00005881 { // acquire lock
5882 std::scoped_lock _l(mLock);
5883
5884 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005885 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5886 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005887 }
5888
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005889 std::shared_ptr<Connection> connection =
5890 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005891 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005892 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005893
5894 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5895 ALOGE("Created a new connection, but the token %p is already known", token.get());
5896 }
5897 mConnectionsByToken.emplace(token, connection);
5898 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5899 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005900
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005901 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005902
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005903 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005904 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005905 }
Garfield Tan15601662020-09-22 15:32:38 -07005906
Michael Wright3dd60e22019-03-27 22:06:44 +00005907 // Wake the looper because some connections have changed.
5908 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005909 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005910}
5911
Garfield Tan15601662020-09-22 15:32:38 -07005912status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005914 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915
Harry Cutts33476232023-01-30 19:57:29 +00005916 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 if (status) {
5918 return status;
5919 }
5920 } // release lock
5921
5922 // Wake the poll loop because removing the connection may have changed the current
5923 // synchronization state.
5924 mLooper->wake();
5925 return OK;
5926}
5927
Garfield Tan15601662020-09-22 15:32:38 -07005928status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5929 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005930 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005931 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005932 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 return BAD_VALUE;
5934 }
5935
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005936 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005937
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005939 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005940 }
5941
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005942 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943
5944 nsecs_t currentTime = now();
5945 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5946
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005947 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 return OK;
5949}
5950
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005951void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005952 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5953 auto& [displayId, monitors] = *it;
5954 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5955 return monitor.inputChannel->getConnectionToken() == connectionToken;
5956 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005957
Michael Wright3dd60e22019-03-27 22:06:44 +00005958 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005959 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005960 } else {
5961 ++it;
5962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963 }
5964}
5965
Michael Wright3dd60e22019-03-27 22:06:44 +00005966status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005968 return pilferPointersLocked(token);
5969}
Michael Wright3dd60e22019-03-27 22:06:44 +00005970
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005971status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005972 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5973 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005974 LOG(WARNING)
5975 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005976 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005977 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005978
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005979 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005980 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005981 LOG(WARNING)
5982 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5983 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005984 return BAD_VALUE;
5985 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005986 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005987 if (deviceIds.empty()) {
5988 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005989 return BAD_VALUE;
5990 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005991
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005992 for (const DeviceId deviceId : deviceIds) {
5993 TouchState& state = *statePtr;
5994 TouchedWindow& window = *windowPtr;
5995 // Send cancel events to all the input channels we're stealing from.
5996 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5997 "input channel stole pointer stream");
5998 options.deviceId = deviceId;
5999 options.displayId = displayId;
6000 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6001 options.pointerIds = pointerIds;
6002 std::string canceledWindows;
6003 for (const TouchedWindow& w : state.windows) {
6004 const std::shared_ptr<InputChannel> channel =
6005 getInputChannelLocked(w.windowHandle->getToken());
6006 if (channel != nullptr && channel->getConnectionToken() != token) {
6007 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6008 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6009 canceledWindows += channel->getName();
6010 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006012 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6013 LOG(INFO) << "Channel " << requestingChannel->getName()
6014 << " is stealing input gesture for device " << deviceId << " from "
6015 << canceledWindows;
6016
6017 // Prevent the gesture from being sent to any other windows.
6018 // This only blocks relevant pointers to be sent to other windows
6019 window.addPilferingPointers(deviceId, pointerIds);
6020
6021 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006022 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006023 return OK;
6024}
6025
Prabir Pradhan99987712020-11-10 18:43:05 -08006026void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6027 { // acquire lock
6028 std::scoped_lock _l(mLock);
6029 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006030 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006031 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6032 windowHandle != nullptr ? windowHandle->getName().c_str()
6033 : "token without window");
6034 }
6035
Vishnu Nairc519ff72021-01-21 08:23:08 -08006036 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006037 if (focusedToken != windowToken) {
6038 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6039 enabled ? "enable" : "disable");
6040 return;
6041 }
6042
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006043 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006044 ALOGW("Ignoring request to %s Pointer Capture: "
6045 "window has %s requested pointer capture.",
6046 enabled ? "enable" : "disable", enabled ? "already" : "not");
6047 return;
6048 }
6049
Christine Franksb768bb42021-11-29 12:11:31 -08006050 if (enabled) {
6051 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6052 mIneligibleDisplaysForPointerCapture.end(),
6053 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6054 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6055 return;
6056 }
6057 }
6058
Prabir Pradhan99987712020-11-10 18:43:05 -08006059 setPointerCaptureLocked(enabled);
6060 } // release lock
6061
6062 // Wake the thread to process command entries.
6063 mLooper->wake();
6064}
6065
Christine Franksb768bb42021-11-29 12:11:31 -08006066void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6067 { // acquire lock
6068 std::scoped_lock _l(mLock);
6069 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6070 if (!isEligible) {
6071 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6072 }
6073 } // release lock
6074}
6075
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006076std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006077 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006078 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006079 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006080 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006081 }
6082 }
6083 }
6084 return std::nullopt;
6085}
6086
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006087std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6088 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006089 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006090 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006091 }
6092
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006093 for (const auto& [token, connection] : mConnectionsByToken) {
6094 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006095 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 }
6097 }
Robert Carr4e670e52018-08-15 13:26:12 -07006098
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006099 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100}
6101
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006102std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006103 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006104 if (connection == nullptr) {
6105 return "<nullptr>";
6106 }
6107 return connection->getInputChannelName();
6108}
6109
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006110void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006111 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006112 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006113}
6114
Prabir Pradhancef936d2021-07-21 16:17:52 +00006115void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006116 const std::shared_ptr<Connection>& connection,
6117 uint32_t seq, bool handled,
6118 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006119 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006120 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006121
6122 { // Start critical section
6123 auto dispatchEntryIt =
6124 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6125 [seq](auto& e) { return e->seq == seq; });
6126 if (dispatchEntryIt == connection->waitQueue.end()) {
6127 return;
6128 }
6129
6130 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6131
6132 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6133 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6134 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6135 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6136 }
6137 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6138 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6139 connection->inputChannel->getConnectionToken(),
6140 dispatchEntry.deliveryTime, consumeTime, finishTime);
6141 }
6142
6143 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006144 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6145 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006146 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006147 }
6148 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006149
6150 // Dequeue the event and start the next cycle.
6151 // Because the lock might have been released, it is possible that the
6152 // contents of the wait queue to have been drained, so we need to double-check
6153 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006154 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6155 [seq](auto& e) { return e->seq == seq; });
6156 if (entryIt != connection->waitQueue.end()) {
6157 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6158 connection->waitQueue.erase(entryIt);
6159
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6161 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6162 if (!connection->responsive) {
6163 connection->responsive = isConnectionResponsive(*connection);
6164 if (connection->responsive) {
6165 // The connection was unresponsive, and now it's responsive.
6166 processConnectionResponsiveLocked(*connection);
6167 }
6168 }
6169 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006170 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6171 const InputTarget target{.inputChannel = connection->inputChannel,
6172 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006173 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006174 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006175 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006176 }
6177
6178 // Start the next dispatch cycle for this connection.
6179 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180}
6181
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6183 const sp<IBinder>& newToken) {
6184 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6185 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006186 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006187 };
6188 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189}
6190
Prabir Pradhancef936d2021-07-21 16:17:52 +00006191void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6192 auto command = [this, token, x, y]() REQUIRES(mLock) {
6193 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006194 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006195 };
6196 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006197}
6198
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006199void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006200 if (connection == nullptr) {
6201 LOG_ALWAYS_FATAL("Caller must check for nullness");
6202 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6204 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006205 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006206 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006207 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 return;
6209 }
6210 /**
6211 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6212 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6213 * has changed. This could cause newer entries to time out before the already dispatched
6214 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6215 * processes the events linearly. So providing information about the oldest entry seems to be
6216 * most useful.
6217 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006218 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6219 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006220 std::string reason =
6221 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006222 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006223 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006224 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006225 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006226 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006227
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006228 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6229
6230 // Stop waking up for events on this connection, it is already unresponsive
6231 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006232}
6233
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006234void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6235 std::string reason =
6236 StringPrintf("%s does not have a focused window", application->getName().c_str());
6237 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006238
Yabin Cui8eb9c552023-06-08 18:05:07 +00006239 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006240 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006241 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 };
6243 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006244}
6245
chaviw98318de2021-05-19 16:45:23 -05006246void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006247 const std::string& reason) {
6248 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6249 updateLastAnrStateLocked(windowLabel, reason);
6250}
6251
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006252void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6253 const std::string& reason) {
6254 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006255 updateLastAnrStateLocked(windowLabel, reason);
6256}
6257
6258void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6259 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006261 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 struct tm tm;
6263 localtime_r(&t, &tm);
6264 char timestr[64];
6265 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006266 mLastAnrState.clear();
6267 mLastAnrState += INDENT "ANR:\n";
6268 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006269 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6270 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006271 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272}
6273
Prabir Pradhancef936d2021-07-21 16:17:52 +00006274void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006275 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006276 const KeyEvent event = createKeyEvent(entry);
6277 nsecs_t delay = 0;
6278 { // release lock
6279 scoped_unlock unlock(mLock);
6280 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006281 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6283 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6284 std::to_string(t.duration().count()).c_str());
6285 }
6286 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287
6288 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006289 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006290 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006291 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006293 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006294 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006296}
6297
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006299 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006300 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006301 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006303 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006304 };
6305 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006306}
6307
Prabir Pradhanedd96402022-02-15 01:46:16 -08006308void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006309 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006310 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006311 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006312 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006313 };
6314 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006315}
6316
6317/**
6318 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6319 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6320 * command entry to the command queue.
6321 */
6322void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6323 std::string reason) {
6324 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006325 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006326 if (connection.monitor) {
6327 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6328 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006329 pid = findMonitorPidByTokenLocked(connectionToken);
6330 } else {
6331 // The connection is a window
6332 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6333 reason.c_str());
6334 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6335 if (handle != nullptr) {
6336 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006337 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006339 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340}
6341
6342/**
6343 * Tell the policy that a connection has become responsive so that it can stop ANR.
6344 */
6345void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6346 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006347 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006349 pid = findMonitorPidByTokenLocked(connectionToken);
6350 } else {
6351 // The connection is a window
6352 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6353 if (handle != nullptr) {
6354 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006355 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006356 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006357 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006358}
6359
Prabir Pradhan24047542023-11-02 17:14:59 +00006360std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006361 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006362 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006363 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006364 if (!handled) {
6365 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006366 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006367 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006368 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006371 // Get the fallback key state.
6372 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006373 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006374 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006375 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006376 connection->inputState.removeFallbackKey(originalKeyCode);
6377 }
6378
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006379 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006380 // If the application handles the original key for which we previously
6381 // generated a fallback or if the window is not a foreground window,
6382 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006383 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006384 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006385 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6386 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6387 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6388 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6389 keyEntry.policyFlags);
6390 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006391 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006392 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393
6394 mLock.unlock();
6395
Prabir Pradhana41d2442023-04-20 21:30:40 +00006396 if (const auto unhandledKeyFallback =
6397 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6398 event, keyEntry.policyFlags);
6399 unhandledKeyFallback) {
6400 event = *unhandledKeyFallback;
6401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402
6403 mLock.lock();
6404
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006405 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006406 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006407 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 "application handled the original non-fallback key "
6409 "or is no longer a foreground target, "
6410 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006411 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006413 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 connection->inputState.removeFallbackKey(originalKeyCode);
6415 }
6416 } else {
6417 // If the application did not handle a non-fallback key, first check
6418 // that we are in a good state to perform unhandled key event processing
6419 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006420 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006421 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006422 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6423 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6424 "since this is not an initial down. "
6425 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6426 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6427 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006428 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006431 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006432 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6433 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6434 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6435 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6436 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006437 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438
6439 mLock.unlock();
6440
Prabir Pradhana41d2442023-04-20 21:30:40 +00006441 bool fallback = false;
6442 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6443 event, keyEntry.policyFlags);
6444 fb) {
6445 fallback = true;
6446 event = *fb;
6447 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006448
6449 mLock.lock();
6450
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006451 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006453 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 }
6455
6456 // Latch the fallback keycode for this key on an initial down.
6457 // The fallback keycode cannot change at any other point in the lifecycle.
6458 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006460 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006462 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006464 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006465 }
6466
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006467 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468
6469 // Cancel the fallback key if the policy decides not to send it anymore.
6470 // We will continue to dispatch the key to the policy but we will no
6471 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006472 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6473 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6475 if (fallback) {
6476 ALOGD("Unhandled key event: Policy requested to send key %d"
6477 "as a fallback for %d, but on the DOWN it had requested "
6478 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006479 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006480 } else {
6481 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6482 "but on the DOWN it had requested to send %d. "
6483 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006484 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006485 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487
Michael Wrightfb04fd52022-11-24 22:31:11 +00006488 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006490 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491 synthesizeCancelationEventsForConnectionLocked(connection, options);
6492
6493 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006495 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006496 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006497 }
6498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006500 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6501 {
6502 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006503 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006504 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006505 for (const auto& [key, value] : fallbackKeys) {
6506 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 }
6508 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6509 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006510 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006511 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512
6513 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006514 // Return the fallback key that we want dispatched to the channel.
6515 std::unique_ptr<KeyEntry> newEntry =
6516 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6517 event.getEventTime(), event.getDeviceId(),
6518 event.getSource(), event.getDisplayId(),
6519 keyEntry.policyFlags, keyEntry.action,
6520 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6521 *fallbackKeyCode, event.getScanCode(),
6522 event.getMetaState(), event.getRepeatCount(),
6523 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006524 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6525 ALOGD("Unhandled key event: Dispatching fallback key. "
6526 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006527 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006528 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006529 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006530 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006531 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6532 ALOGD("Unhandled key event: No fallback key.");
6533 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006534
6535 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006536 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 }
6538 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006539 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540}
6541
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542void InputDispatcher::traceInboundQueueLengthLocked() {
6543 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006544 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545 }
6546}
6547
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006548void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006549 if (ATRACE_ENABLED()) {
6550 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006551 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6552 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553 }
6554}
6555
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006556void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 if (ATRACE_ENABLED()) {
6558 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006559 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6560 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006561 }
6562}
6563
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006564void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006565 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006567 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006568 dumpDispatchStateLocked(dump);
6569
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006570 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006571 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006572 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 }
6574}
6575
6576void InputDispatcher::monitor() {
6577 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006578 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006580 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581}
6582
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006583/**
6584 * Wake up the dispatcher and wait until it processes all events and commands.
6585 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6586 * this method can be safely called from any thread, as long as you've ensured that
6587 * the work you are interested in completing has already been queued.
6588 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006589bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006590 /**
6591 * Timeout should represent the longest possible time that a device might spend processing
6592 * events and commands.
6593 */
6594 constexpr std::chrono::duration TIMEOUT = 100ms;
6595 std::unique_lock lock(mLock);
6596 mLooper->wake();
6597 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6598 return result == std::cv_status::no_timeout;
6599}
6600
Vishnu Naire798b472020-07-23 13:52:21 -07006601/**
6602 * Sets focus to the window identified by the token. This must be called
6603 * after updating any input window handles.
6604 *
6605 * Params:
6606 * request.token - input channel token used to identify the window that should gain focus.
6607 * request.focusedToken - the token that the caller expects currently to be focused. If the
6608 * specified token does not match the currently focused window, this request will be dropped.
6609 * If the specified focused token matches the currently focused window, the call will succeed.
6610 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6611 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6612 * when requesting the focus change. This determines which request gets
6613 * precedence if there is a focus change request from another source such as pointer down.
6614 */
Vishnu Nair958da932020-08-21 17:12:37 -07006615void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6616 { // acquire lock
6617 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006618 std::optional<FocusResolver::FocusChanges> changes =
6619 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6620 if (changes) {
6621 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006622 }
6623 } // release lock
6624 // Wake up poll loop since it may need to make new input dispatching choices.
6625 mLooper->wake();
6626}
6627
Vishnu Nairc519ff72021-01-21 08:23:08 -08006628void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6629 if (changes.oldFocus) {
6630 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006631 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006632 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006633 "focus left window");
6634 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006635 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006636 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006637 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006638 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006639 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006640 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006641 }
6642
Prabir Pradhan99987712020-11-10 18:43:05 -08006643 // If a window has pointer capture, then it must have focus. We need to ensure that this
6644 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6645 // If the window loses focus before it loses pointer capture, then the window can be in a state
6646 // where it has pointer capture but not focus, violating the contract. Therefore we must
6647 // dispatch the pointer capture event before the focus event. Since focus events are added to
6648 // the front of the queue (above), we add the pointer capture event to the front of the queue
6649 // after the focus events are added. This ensures the pointer capture event ends up at the
6650 // front.
6651 disablePointerCaptureForcedLocked();
6652
Vishnu Nairc519ff72021-01-21 08:23:08 -08006653 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006654 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006655 }
6656}
Vishnu Nair958da932020-08-21 17:12:37 -07006657
Prabir Pradhan99987712020-11-10 18:43:05 -08006658void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006659 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006660 return;
6661 }
6662
6663 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6664
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006665 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006666 setPointerCaptureLocked(false);
6667 }
6668
6669 if (!mWindowTokenWithPointerCapture) {
6670 // No need to send capture changes because no window has capture.
6671 return;
6672 }
6673
6674 if (mPendingEvent != nullptr) {
6675 // Move the pending event to the front of the queue. This will give the chance
6676 // for the pending event to be dropped if it is a captured event.
6677 mInboundQueue.push_front(mPendingEvent);
6678 mPendingEvent = nullptr;
6679 }
6680
6681 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006682 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006683 mInboundQueue.push_front(std::move(entry));
6684}
6685
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006686void InputDispatcher::setPointerCaptureLocked(bool enable) {
6687 mCurrentPointerCaptureRequest.enable = enable;
6688 mCurrentPointerCaptureRequest.seq++;
6689 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006690 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006691 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006692 };
6693 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006694}
6695
Vishnu Nair599f1412021-06-21 10:39:58 -07006696void InputDispatcher::displayRemoved(int32_t displayId) {
6697 { // acquire lock
6698 std::scoped_lock _l(mLock);
6699 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006700 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006701 setFocusedApplicationLocked(displayId, nullptr);
6702 // Call focus resolver to clean up stale requests. This must be called after input windows
6703 // have been removed for the removed display.
6704 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006705 // Reset pointer capture eligibility, regardless of previous state.
6706 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006707 // Remove the associated touch mode state.
6708 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006709 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006710 } // release lock
6711
6712 // Wake up poll loop since it may need to make new input dispatching choices.
6713 mLooper->wake();
6714}
6715
Patrick Williamsd828f302023-04-28 17:52:08 -05006716void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006717 // The listener sends the windows as a flattened array. Separate the windows by display for
6718 // more convenient parsing.
6719 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006720 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006721 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006722 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006723 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006724
6725 { // acquire lock
6726 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006727
6728 // Ensure that we have an entry created for all existing displays so that if a displayId has
6729 // no windows, we can tell that the windows were removed from the display.
6730 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6731 handlesPerDisplay[displayId];
6732 }
6733
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006734 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006735 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006736 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6737 }
6738
6739 for (const auto& [displayId, handles] : handlesPerDisplay) {
6740 setInputWindowsLocked(handles, displayId);
6741 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006742
6743 if (update.vsyncId < mWindowInfosVsyncId) {
6744 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6745 ", current update vsync id: %" PRId64,
6746 mWindowInfosVsyncId, update.vsyncId);
6747 }
6748 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006749 }
6750 // Wake up poll loop since it may need to make new input dispatching choices.
6751 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006752}
6753
Vishnu Nair062a8672021-09-03 16:07:44 -07006754bool InputDispatcher::shouldDropInput(
6755 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006756 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6757 (windowHandle->getInfo()->inputConfig.test(
6758 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006759 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006760 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6761 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006762 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006763 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006764 windowHandle->getInfo()->displayId);
6765 return true;
6766 }
6767 return false;
6768}
6769
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006770void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006771 const gui::WindowInfosUpdate& update) {
6772 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006773}
6774
Arthur Hungdfd528e2021-12-08 13:23:04 +00006775void InputDispatcher::cancelCurrentTouch() {
6776 {
6777 std::scoped_lock _l(mLock);
6778 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006779 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006780 "cancel current touch");
6781 synthesizeCancelationEventsForAllConnectionsLocked(options);
6782
6783 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006784 }
6785 // Wake up poll loop since there might be work to do.
6786 mLooper->wake();
6787}
6788
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006789void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6790 std::scoped_lock _l(mLock);
6791 mMonitorDispatchingTimeout = timeout;
6792}
6793
Arthur Hungc539dbb2022-12-08 07:45:36 +00006794void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6795 const sp<WindowInfoHandle>& oldWindowHandle,
6796 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006797 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006798 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006799 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6800 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006801 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6802 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6803 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6804 newWindowHandle->getInfo()->inputConfig.test(
6805 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6806 const sp<WindowInfoHandle> oldWallpaper =
6807 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6808 const sp<WindowInfoHandle> newWallpaper =
6809 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6810 if (oldWallpaper == newWallpaper) {
6811 return;
6812 }
6813
6814 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006815 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006816 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
6817 oldTouchedWindow.targetFlags, pointerIds,
6818 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006819 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006820 }
6821
6822 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006823 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6824 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006825 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006826 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006827 }
6828}
6829
6830void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6831 ftl::Flags<InputTarget::Flags> newTargetFlags,
6832 const sp<WindowInfoHandle> fromWindowHandle,
6833 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006834 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006835 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006836 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6837 fromWindowHandle->getInfo()->inputConfig.test(
6838 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6839 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6840 toWindowHandle->getInfo()->inputConfig.test(
6841 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6842
6843 const sp<WindowInfoHandle> oldWallpaper =
6844 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6845 const sp<WindowInfoHandle> newWallpaper =
6846 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6847 if (oldWallpaper == newWallpaper) {
6848 return;
6849 }
6850
6851 if (oldWallpaper != nullptr) {
6852 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6853 "transferring touch focus to another window");
6854 state.removeWindowByToken(oldWallpaper->getToken());
6855 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6856 }
6857
6858 if (newWallpaper != nullptr) {
6859 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006860 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006861 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6862 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006863 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
6864 deviceId, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006865 std::shared_ptr<Connection> wallpaperConnection =
6866 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006867 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006868 std::shared_ptr<Connection> toConnection =
6869 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006870 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6871 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6872 wallpaperFlags);
6873 }
6874 }
6875}
6876
6877sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6878 const sp<WindowInfoHandle>& windowHandle) const {
6879 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6880 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6881 bool foundWindow = false;
6882 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6883 if (!foundWindow && otherHandle != windowHandle) {
6884 continue;
6885 }
6886 if (windowHandle == otherHandle) {
6887 foundWindow = true;
6888 continue;
6889 }
6890
6891 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6892 return otherHandle;
6893 }
6894 }
6895 return nullptr;
6896}
6897
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006898void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6899 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006900 std::scoped_lock _l(mLock);
6901
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006902 mConfig.keyRepeatTimeout = timeout.count();
6903 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006904}
6905
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006906bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6907 DeviceId deviceId, int32_t pointerId) {
6908 std::scoped_lock _l(mLock);
6909 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6910 if (touchStateIt == mTouchStatesByDisplay.end()) {
6911 return false;
6912 }
6913 for (const TouchedWindow& window : touchStateIt->second.windows) {
6914 if (window.windowHandle->getToken() == token &&
6915 (window.hasTouchingPointer(deviceId, pointerId) ||
6916 window.hasHoveringPointer(deviceId, pointerId))) {
6917 return true;
6918 }
6919 }
6920 return false;
6921}
6922
Garfield Tane84e6f92019-08-29 17:28:41 -07006923} // namespace android::inputdispatcher