blob: 341d146249dc7268def7d9e1c9eac5b11f282d36 [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
Garfield Tane84e6f92019-08-29 17:28:41 -070075namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Prabir Pradhancef936d2021-07-21 16:17:52 +000077namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000078// Temporarily releases a held mutex for the lifetime of the instance.
79// Named to match std::scoped_lock
80class scoped_unlock {
81public:
82 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
83 ~scoped_unlock() { mMutex.lock(); }
84
85private:
86 std::mutex& mMutex;
87};
88
Michael Wrightd02c5b62014-02-10 15:10:22 -080089// Default input dispatching timeout if there is no focused application or paused window
90// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080091const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
92 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
93 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800100const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102// 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 +0000103constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
104
105// Log a warning when an interception call takes longer than this to process.
106constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700108// Additional key latency in case a connection is still processing some motion events.
109// This will help with the case when a user touched a button that opens a new window,
110// and gives us the chance to dispatch the key to this new window.
111constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
112
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000114constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
115
Antonio Kantekea47acb2021-12-23 12:41:25 -0800116// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000117constexpr int LOGTAG_INPUT_INTERACTION = 62000;
118constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000119constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000120
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000121const ui::Transform kIdentityTransform;
122
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000123inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124 return systemTime(SYSTEM_TIME_MONOTONIC);
125}
126
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700127bool isEmpty(const std::stringstream& ss) {
128 return ss.rdbuf()->in_avail() == 0;
129}
130
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700131inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000132 if (binder == nullptr) {
133 return "<null>";
134 }
135 return StringPrintf("%p", binder.get());
136}
137
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000138static std::string uidString(const gui::Uid& uid) {
139 return uid.toString();
140}
141
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> validateKeyEvent(int32_t action) {
153 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154}
155
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700156Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800157 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_UP: {
160 if (pointerCount != 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_HOVER_ENTER:
167 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
169 if (pointerCount < 1) {
170 return Error() << "invalid pointer count " << pointerCount;
171 }
172 return {};
173 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800174 case AMOTION_EVENT_ACTION_CANCEL:
175 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800180 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700181 if (index < 0) {
182 return Error() << "invalid index " << index << " for "
183 << MotionEvent::actionToString(action);
184 }
185 if (index >= pointerCount) {
186 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
187 }
188 if (pointerCount <= 1) {
189 return Error() << "invalid pointer count " << pointerCount << " for "
190 << MotionEvent::actionToString(action);
191 }
192 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 }
194 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700195 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
196 if (actionButton == 0) {
197 return Error() << "action button should be nonzero for "
198 << MotionEvent::actionToString(action);
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700203 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500208 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
209}
210
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700211Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
212 const PointerProperties* pointerProperties) {
213 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
214 if (!actionCheck.ok()) {
215 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 return Error() << "Motion event has invalid pointer count " << pointerCount
219 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800221 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 for (size_t i = 0; i < pointerCount; i++) {
223 int32_t id = pointerProperties[i].id;
224 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer id " << id
226 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800231 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700233 return {};
234}
235
236Result<void> validateInputEvent(const InputEvent& event) {
237 switch (event.getType()) {
238 case InputEventType::KEY: {
239 const KeyEvent& key = static_cast<const KeyEvent&>(event);
240 const int32_t action = key.getAction();
241 return validateKeyEvent(action);
242 }
243 case InputEventType::MOTION: {
244 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
245 const int32_t action = motion.getAction();
246 const size_t pointerCount = motion.getPointerCount();
247 const PointerProperties* pointerProperties = motion.getPointerProperties();
248 const int32_t actionButton = motion.getActionButton();
249 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
250 }
251 default: {
252 return {};
253 }
254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255}
256
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000257std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000259 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 }
261
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000262 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 bool first = true;
264 Region::const_iterator cur = region.begin();
265 Region::const_iterator const tail = region.end();
266 while (cur != tail) {
267 if (first) {
268 first = false;
269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800272 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 cur++;
274 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000275 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276}
277
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000278std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
279 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500280 constexpr size_t maxEntries = 50; // max events to print
281 constexpr size_t skipBegin = maxEntries / 2;
282 const size_t skipEnd = queue.size() - maxEntries / 2;
283 // skip from maxEntries / 2 ... size() - maxEntries/2
284 // only print from 0 .. skipBegin and then from skipEnd .. size()
285
286 std::string dump;
287 for (size_t i = 0; i < queue.size(); i++) {
288 const DispatchEntry& entry = *queue[i];
289 if (i >= skipBegin && i < skipEnd) {
290 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
291 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
292 continue;
293 }
294 dump.append(INDENT4);
295 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800296 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
297 "ms",
298 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500299 ns2ms(currentTime - entry.eventEntry->eventTime));
300 if (entry.deliveryTime != 0) {
301 // This entry was delivered, so add information on how long we've been waiting
302 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
303 }
304 dump.append("\n");
305 }
306 return dump;
307}
308
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700309/**
310 * Find the entry in std::unordered_map by key, and return it.
311 * If the entry is not found, return a default constructed entry.
312 *
313 * Useful when the entries are vectors, since an empty vector will be returned
314 * if the entry is not found.
315 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
316 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700317template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700319 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700320 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800321}
322
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000323bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700324 if (first == second) {
325 return true;
326 }
327
328 if (first == nullptr || second == nullptr) {
329 return false;
330 }
331
332 return first->getToken() == second->getToken();
333}
334
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000335bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000336 if (first == nullptr || second == nullptr) {
337 return false;
338 }
339 return first->applicationInfo.token != nullptr &&
340 first->applicationInfo.token == second->applicationInfo.token;
341}
342
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800343template <typename T>
344size_t firstMarkedBit(T set) {
345 // TODO: replace with std::countr_zero from <bit> when that's available
346 LOG_ALWAYS_FATAL_IF(set.none());
347 size_t i = 0;
348 while (!set.test(i)) {
349 i++;
350 }
351 return i;
352}
353
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800354std::unique_ptr<DispatchEntry> createDispatchEntry(
355 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
356 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 if (inputTarget.useDefaultPointerTransform()) {
358 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700359 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700360 inputTarget.displayTransform,
361 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000362 }
363
364 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
365 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700368 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000369
370 // Use the first pointer information to normalize all other pointers. This could be any pointer
371 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 // uses the transform for the normalized pointer.
373 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800374 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376
377 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700378 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
380 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700381 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382
383 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700384 // First, apply the current pointer's transform to update the coordinates into
385 // window space.
386 pointerCoords[pointerIndex].transform(currTransform);
387 // Next, apply the inverse transform of the normalized coordinates so the
388 // current coordinates are transformed into the normalized coordinate space.
389 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 }
391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700392 std::unique_ptr<MotionEntry> combinedMotionEntry =
393 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
394 motionEntry.deviceId, motionEntry.source,
395 motionEntry.displayId, motionEntry.policyFlags,
396 motionEntry.action, motionEntry.actionButton,
397 motionEntry.flags, motionEntry.metaState,
398 motionEntry.buttonState, motionEntry.classification,
399 motionEntry.edgeFlags, motionEntry.xPrecision,
400 motionEntry.yPrecision, motionEntry.xCursorPosition,
401 motionEntry.yCursorPosition, motionEntry.downTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700402 motionEntry.pointerProperties, pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
404 if (motionEntry.injectionState) {
405 combinedMotionEntry->injectionState = motionEntry.injectionState;
406 combinedMotionEntry->injectionState->refCount += 1;
407 }
408
409 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700410 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700411 firstPointerTransform, inputTarget.displayTransform,
412 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000413 return dispatchEntry;
414}
415
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000416status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
417 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700418 std::unique_ptr<InputChannel> uniqueServerChannel;
419 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
420
421 serverChannel = std::move(uniqueServerChannel);
422 return result;
423}
424
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500425template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000426bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500427 if (lhs == nullptr && rhs == nullptr) {
428 return true;
429 }
430 if (lhs == nullptr || rhs == nullptr) {
431 return false;
432 }
433 return *lhs == *rhs;
434}
435
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000437 KeyEvent event;
438 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
439 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
440 entry.repeatCount, entry.downTime, entry.eventTime);
441 return event;
442}
443
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000444bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000445 // Do not keep track of gesture monitors. They receive every event and would disproportionately
446 // affect the statistics.
447 if (connection.monitor) {
448 return false;
449 }
450 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
451 if (!connection.responsive) {
452 return false;
453 }
454 return true;
455}
456
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000457bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000458 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
459 const int32_t& inputEventId = eventEntry.id;
460 if (inputEventId != dispatchEntry.resolvedEventId) {
461 // Event was transmuted
462 return false;
463 }
464 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
465 return false;
466 }
467 // Only track latency for events that originated from hardware
468 if (eventEntry.isSynthesized()) {
469 return false;
470 }
471 const EventEntry::Type& inputEventEntryType = eventEntry.type;
472 if (inputEventEntryType == EventEntry::Type::KEY) {
473 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
474 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
475 return false;
476 }
477 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
478 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
479 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
480 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
481 return false;
482 }
483 } else {
484 // Not a key or a motion
485 return false;
486 }
487 if (!shouldReportMetricsForConnection(connection)) {
488 return false;
489 }
490 return true;
491}
492
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493/**
494 * Connection is responsive if it has no events in the waitQueue that are older than the
495 * current time.
496 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000497bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000499 for (const auto& dispatchEntry : connection.waitQueue) {
500 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000501 return false;
502 }
503 }
504 return true;
505}
506
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507// Returns true if the event type passed as argument represents a user activity.
508bool isUserActivityEvent(const EventEntry& eventEntry) {
509 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000510 case EventEntry::Type::CONFIGURATION_CHANGED:
511 case EventEntry::Type::DEVICE_RESET:
512 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::FOCUS:
514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::KEY:
519 case EventEntry::Type::MOTION:
520 return true;
521 }
522}
523
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000525bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800527 const auto inputConfig = windowInfo.inputConfig;
528 if (windowInfo.displayId != displayId ||
529 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700532 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800534 return false;
535 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000536
537 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
538 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
539 // the window. Points on the right and bottom edges should not be inside the window, so we need
540 // to be careful about performing a hit test when the display is rotated, since the "right" and
541 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
542 // logical display in which WM determined the bounds. Perform the hit test in the logical
543 // display space to ensure these edges are considered correctly in all orientations.
544 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
545 const auto p = displayTransform.transform(x, y);
546 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800547 return false;
548 }
549 return true;
550}
551
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
553 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000554 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700555}
556
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
559// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
560// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800561// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000562bool canReceiveForegroundTouches(const WindowInfo& info) {
563 // A non-touchable window can still receive touch events (e.g. in the case of
564 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
565 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
566}
567
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000568bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700569 if (windowHandle == nullptr) {
570 return false;
571 }
572 const WindowInfo* windowInfo = windowHandle->getInfo();
573 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
574 return true;
575 }
576 return false;
577}
578
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579// Checks targeted injection using the window's owner's uid.
580// Returns an empty string if an entry can be sent to the given window, or an error message if the
581// entry is a targeted injection whose uid target doesn't match the window owner.
582std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
583 const EventEntry& entry) {
584 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
585 // The event was not injected, or the injected event does not target a window.
586 return {};
587 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000588 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("No valid window target for injection into uid %s.",
591 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000592 }
593 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
595 "owned by uid %s.",
596 uid.toString().c_str(), window->getName().c_str(),
597 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 return {};
600}
601
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
604 // Always dispatch mouse events to cursor position.
605 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607 }
608
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700609 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000610 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
611 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612}
613
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700614std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
615 if (eventEntry.type == EventEntry::Type::KEY) {
616 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
617 return keyEntry.downTime;
618 } else if (eventEntry.type == EventEntry::Type::MOTION) {
619 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
620 return motionEntry.downTime;
621 }
622 return std::nullopt;
623}
624
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000625/**
626 * Compare the old touch state to the new touch state, and generate the corresponding touched
627 * windows (== input targets).
628 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
629 * If the pointer just entered the new window, produce HOVER_ENTER.
630 * For pointers remaining in the window, produce HOVER_MOVE.
631 */
632std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
633 const TouchState& newTouchState,
634 const MotionEntry& entry) {
635 std::vector<TouchedWindow> out;
636 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700637
638 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
639 // ACTION_SCROLL events should not affect the hovering pointer dispatch
640 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000641 }
642
643 // We should consider all hovering pointers here. But for now, just use the first one
644 const int32_t pointerId = entry.pointerProperties[0].id;
645
646 std::set<sp<WindowInfoHandle>> oldWindows;
647 if (oldState != nullptr) {
648 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
649 }
650
651 std::set<sp<WindowInfoHandle>> newWindows =
652 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
653
654 // If the pointer is no longer in the new window set, send HOVER_EXIT.
655 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
656 if (newWindows.find(oldWindow) == newWindows.end()) {
657 TouchedWindow touchedWindow;
658 touchedWindow.windowHandle = oldWindow;
659 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 out.push_back(touchedWindow);
661 }
662 }
663
664 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
665 TouchedWindow touchedWindow;
666 touchedWindow.windowHandle = newWindow;
667 if (oldWindows.find(newWindow) == oldWindows.end()) {
668 // Any windows that have this pointer now, and didn't have it before, should get
669 // HOVER_ENTER
670 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
671 } else {
672 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700674 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000675 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
676 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700677 // The Accessibility injected touch exploration event stream
678 // has known inconsistencies, so log ERROR instead of
679 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700680 severity = android::base::LogSeverity::ERROR;
681 }
682 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700683 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
685 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700686 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000687 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
688 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
689 }
690 out.push_back(touchedWindow);
691 }
692 return out;
693}
694
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800695template <typename T>
696std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
697 left.insert(left.end(), right.begin(), right.end());
698 return left;
699}
700
Harry Cuttsb166c002023-05-09 13:06:05 +0000701// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
702// both.
703void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
704 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
705 if (!window.windowHandle->getInfo()->inputConfig.test(
706 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
707 // In addition to TouchState, erase this window from the input targets! We don't have a
708 // good way to do this today except by adding a nested loop.
709 // TODO(b/282025641): simplify this code once InputTargets are being identified
710 // separately from TouchedWindows.
711 std::erase_if(targets, [&](const InputTarget& target) {
712 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
713 });
714 return true;
715 }
716 return false;
717 });
718}
719
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700720/**
721 * In general, touch should be always split between windows. Some exceptions:
722 * 1. Don't split touch if all of the below is true:
723 * (a) we have an active pointer down *and*
724 * (b) a new pointer is going down that's from the same device *and*
725 * (c) the window that's receiving the current pointer does not support split touch.
726 * 2. Don't split mouse events
727 */
728bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
729 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
730 // We should never split mouse events
731 return false;
732 }
733 for (const TouchedWindow& touchedWindow : touchState.windows) {
734 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
735 // Spy windows should not affect whether or not touch is split.
736 continue;
737 }
738 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
739 continue;
740 }
741 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
742 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
743 // Wallpaper window should not affect whether or not touch is split
744 continue;
745 }
746
747 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
748 return false;
749 }
750 }
751 return true;
752}
753
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000754} // namespace
755
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756// --- InputDispatcher ---
757
Prabir Pradhana41d2442023-04-20 21:30:40 +0000758InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Garfield Tan00f511d2019-06-12 16:55:40 -0700759 : mPolicy(policy),
760 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700761 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800762 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700763 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700764 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700765 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800766 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mDispatchEnabled(false),
768 mDispatchFrozen(false),
769 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100770 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000771 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800772 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000773 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000774 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700775 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800776 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700778 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700779#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700780 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700781#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700782 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783}
784
785InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000786 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787
Prabir Pradhancef936d2021-07-21 16:17:52 +0000788 resetKeyRepeatLocked();
789 releasePendingEventLocked();
790 drainInboundQueueLocked();
791 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000793 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700794 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000795 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797}
798
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700799status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700800 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700801 return ALREADY_EXISTS;
802 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700803 mThread = std::make_unique<InputThread>(
804 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
805 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700806}
807
808status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700809 if (mThread && mThread->isCallingThread()) {
810 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700811 return INVALID_OPERATION;
812 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700813 mThread.reset();
814 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700815}
816
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700818 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800820 std::scoped_lock _l(mLock);
821 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822
823 // Run a dispatch loop if there are no pending commands.
824 // The dispatch loop might enqueue commands to run afterwards.
825 if (!haveCommandsLocked()) {
826 dispatchOnceInnerLocked(&nextWakeupTime);
827 }
828
829 // Run all pending commands if there are any.
830 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000831 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700832 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800834
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700835 // If we are still waiting for ack on some events,
836 // we might have to wake up earlier to check if an app is anr'ing.
837 const nsecs_t nextAnrCheck = processAnrsLocked();
838 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
839
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800840 // We are about to enter an infinitely long sleep, because we have no commands or
841 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700842 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800843 mDispatcherEnteredIdle.notify_all();
844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 } // release lock
846
847 // Wait for callback or timeout or wake. (make sure we round up, not down)
848 nsecs_t currentTime = now();
849 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
850 mLooper->pollOnce(timeoutMillis);
851}
852
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700853/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500854 * Raise ANR if there is no focused window.
855 * Before the ANR is raised, do a final state check:
856 * 1. The currently focused application must be the same one we are waiting for.
857 * 2. Ensure we still don't have a focused window.
858 */
859void InputDispatcher::processNoFocusedWindowAnrLocked() {
860 // Check if the application that we are waiting for is still focused.
861 std::shared_ptr<InputApplicationHandle> focusedApplication =
862 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
863 if (focusedApplication == nullptr ||
864 focusedApplication->getApplicationToken() !=
865 mAwaitedFocusedApplication->getApplicationToken()) {
866 // Unexpected because we should have reset the ANR timer when focused application changed
867 ALOGE("Waited for a focused window, but focused application has already changed to %s",
868 focusedApplication->getName().c_str());
869 return; // The focused application has changed.
870 }
871
chaviw98318de2021-05-19 16:45:23 -0500872 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500873 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
874 if (focusedWindowHandle != nullptr) {
875 return; // We now have a focused window. No need for ANR.
876 }
877 onAnrLocked(mAwaitedFocusedApplication);
878}
879
880/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700881 * Check if any of the connections' wait queues have events that are too old.
882 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
883 * Return the time at which we should wake up next.
884 */
885nsecs_t InputDispatcher::processAnrsLocked() {
886 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700887 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700888 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
889 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
890 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500891 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700892 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500893 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700894 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500896 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700897 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
898 }
899 }
900
901 // Check if any connection ANRs are due
902 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
903 if (currentTime < nextAnrCheck) { // most likely scenario
904 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
905 }
906
907 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700908 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700909 if (connection == nullptr) {
910 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
911 return nextAnrCheck;
912 }
913 connection->responsive = false;
914 // Stop waking up for this unresponsive connection
915 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000916 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700917 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700918}
919
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800920std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700921 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800922 if (connection->monitor) {
923 return mMonitorDispatchingTimeout;
924 }
925 const sp<WindowInfoHandle> window =
926 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500928 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500930 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931}
932
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
934 nsecs_t currentTime = now();
935
Jeff Browndc5992e2014-04-11 01:27:26 -0700936 // Reset the key repeat timer whenever normal dispatch is suspended while the
937 // device is in a non-interactive state. This is to ensure that we abort a key
938 // repeat if the device is just coming out of sleep.
939 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 resetKeyRepeatLocked();
941 }
942
943 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
944 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100945 if (DEBUG_FOCUS) {
946 ALOGD("Dispatch frozen. Waiting some more.");
947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 return;
949 }
950
951 // Optimize latency of app switches.
952 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
953 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
954 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
955 if (mAppSwitchDueTime < *nextWakeupTime) {
956 *nextWakeupTime = mAppSwitchDueTime;
957 }
958
959 // Ready to start a new event.
960 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700962 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 if (isAppSwitchDue) {
964 // The inbound queue is empty so the app switch key we were waiting
965 // for will never arrive. Stop waiting for it.
966 resetPendingAppSwitchLocked(false);
967 isAppSwitchDue = false;
968 }
969
970 // Synthesize a key repeat if appropriate.
971 if (mKeyRepeatState.lastKeyEntry) {
972 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
973 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
974 } else {
975 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
976 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
977 }
978 }
979 }
980
981 // Nothing to do if there is no pending event.
982 if (!mPendingEvent) {
983 return;
984 }
985 } else {
986 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700987 mPendingEvent = mInboundQueue.front();
988 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 traceInboundQueueLengthLocked();
990 }
991
992 // Poke user activity for this event.
993 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700994 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
997
998 // Now we have an event to dispatch.
999 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001000 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001002 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001006 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 }
1008
1009 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012
1013 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001014 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001015 const ConfigurationChangedEntry& typedEntry =
1016 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001018 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 break;
1020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001022 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001023 const DeviceResetEntry& typedEntry =
1024 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001026 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 break;
1028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001030 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001031 std::shared_ptr<FocusEntry> typedEntry =
1032 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 dispatchFocusLocked(currentTime, typedEntry);
1034 done = true;
1035 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1036 break;
1037 }
1038
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001039 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1040 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1041 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1042 done = true;
1043 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1044 break;
1045 }
1046
Prabir Pradhan99987712020-11-10 18:43:05 -08001047 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1048 const auto typedEntry =
1049 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1050 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1051 done = true;
1052 break;
1053 }
1054
arthurhungb89ccb02020-12-30 16:19:01 +08001055 case EventEntry::Type::DRAG: {
1056 std::shared_ptr<DragEntry> typedEntry =
1057 std::static_pointer_cast<DragEntry>(mPendingEvent);
1058 dispatchDragLocked(currentTime, typedEntry);
1059 done = true;
1060 break;
1061 }
1062
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001063 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001064 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001066 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 resetPendingAppSwitchLocked(true);
1068 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 } else if (dropReason == DropReason::NOT_DROPPED) {
1070 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 }
1072 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001073 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1077 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001079 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 break;
1081 }
1082
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001083 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 std::shared_ptr<MotionEntry> motionEntry =
1085 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1087 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001090 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001092 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1093 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001095 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
Chris Yef59a2f42020-10-16 12:55:26 -07001098
1099 case EventEntry::Type::SENSOR: {
1100 std::shared_ptr<SensorEntry> sensorEntry =
1101 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1102 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1103 dropReason = DropReason::APP_SWITCH;
1104 }
1105 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1106 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1107 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1108 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1109 dropReason = DropReason::STALE;
1110 }
1111 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1112 done = true;
1113 break;
1114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
1116
1117 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001119 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
Michael Wright3a981722015-06-10 15:26:13 +01001121 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122
1123 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001124 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126}
1127
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001128bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001129 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001130}
1131
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001132/**
1133 * Return true if the events preceding this incoming motion event should be dropped
1134 * Return false otherwise (the default behaviour)
1135 */
1136bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001137 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001138 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001139
1140 // Optimize case where the current application is unresponsive and the user
1141 // decides to touch a window in a different application.
1142 // If the application takes too long to catch up then we drop all events preceding
1143 // the touch into the other window.
1144 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001145 const int32_t displayId = motionEntry.displayId;
1146 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001147 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001148
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001149 sp<WindowInfoHandle> touchedWindowHandle =
1150 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001151 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001152 touchedWindowHandle->getApplicationToken() !=
1153 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001155 ALOGI("Pruning input queue because user touched a different application while waiting "
1156 "for %s",
1157 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001158 return true;
1159 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001160
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001161 // Alternatively, maybe there's a spy window that could handle this event.
1162 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1163 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1164 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001165 const std::shared_ptr<Connection> connection =
1166 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001167 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001168 // This spy window could take more input. Drop all events preceding this
1169 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001170 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001171 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001172 mAwaitedFocusedApplication->getName().c_str());
1173 return true;
1174 }
1175 }
1176 }
1177
1178 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1179 // yet been processed by some connections, the dispatcher will wait for these motion
1180 // events to be processed before dispatching the key event. This is because these motion events
1181 // may cause a new window to be launched, which the user might expect to receive focus.
1182 // To prevent waiting forever for such events, just send the key to the currently focused window
1183 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1184 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1185 "just send the pending key event to the focused window.");
1186 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001187 }
1188 return false;
1189}
1190
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193 mInboundQueue.push_back(std::move(newEntry));
1194 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 traceInboundQueueLengthLocked();
1196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001198 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001199 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1200 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 // Optimize app switch latency.
1202 // If the application takes too long to catch up then we drop all events preceding
1203 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001205 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001206 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001208 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001209 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001210 if (DEBUG_APP_SWITCH) {
1211 ALOGD("App switch is pending!");
1212 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 mAppSwitchSawKeyDown = false;
1215 needWake = true;
1216 }
1217 }
1218 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001219
1220 // If a new up event comes in, and the pending event with same key code has been asked
1221 // to try again later because of the policy. We have to reset the intercept key wake up
1222 // time for it may have been handled in the policy and could be dropped.
1223 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1224 mPendingEvent->type == EventEntry::Type::KEY) {
1225 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1226 if (pendingKey.keyCode == keyEntry.keyCode &&
1227 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001228 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1229 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001230 pendingKey.interceptKeyWakeupTime = 0;
1231 needWake = true;
1232 }
1233 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001234 break;
1235 }
1236
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001237 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001238 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1239 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001240 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1241 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001242 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001246 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1248 break;
1249 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001250 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001251 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001252 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001253 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001254 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1255 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001256 // nothing to do
1257 break;
1258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
1260
1261 return needWake;
1262}
1263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001265 // Do not store sensor event in recent queue to avoid flooding the queue.
1266 if (entry->type != EventEntry::Type::SENSOR) {
1267 mRecentQueue.push_back(entry);
1268 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001269 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001270 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 }
1272}
1273
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001274sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1275 bool isStylus,
1276 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001278 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001279 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001280 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001281 continue;
1282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001284 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001285 if (!info.isSpy() &&
1286 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001287 return windowHandle;
1288 }
1289 }
1290 return nullptr;
1291}
1292
1293std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001294 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001295 if (touchedWindow == nullptr) {
1296 return {};
1297 }
1298 // Traverse windows from front to back until we encounter the touched window.
1299 std::vector<InputTarget> outsideTargets;
1300 const auto& windowHandles = getWindowHandlesLocked(displayId);
1301 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1302 if (windowHandle == touchedWindow) {
1303 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1304 // below the touched window will not get ACTION_OUTSIDE event.
1305 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001306 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001307
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001308 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001309 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001310 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1311 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001312 addPointerWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1313 pointerIds,
1314 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001317 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318}
1319
Prabir Pradhand65552b2021-10-07 11:23:50 -07001320std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001321 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001322 // Traverse windows from front to back and gather the touched spy windows.
1323 std::vector<sp<WindowInfoHandle>> spyWindows;
1324 const auto& windowHandles = getWindowHandlesLocked(displayId);
1325 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1326 const WindowInfo& info = *windowHandle->getInfo();
1327
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001328 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001329 continue;
1330 }
1331 if (!info.isSpy()) {
1332 // The first touched non-spy window was found, so return the spy windows touched so far.
1333 return spyWindows;
1334 }
1335 spyWindows.push_back(windowHandle);
1336 }
1337 return spyWindows;
1338}
1339
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001340void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 const char* reason;
1342 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001343 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001344 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001345 ALOGD("Dropped event because policy consumed it.");
1346 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 reason = "inbound event was dropped because the policy consumed it";
1348 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001349 case DropReason::DISABLED:
1350 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001351 ALOGI("Dropped event because input dispatch is disabled.");
1352 }
1353 reason = "inbound event was dropped because input dispatch is disabled";
1354 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001355 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 ALOGI("Dropped event because of pending overdue app switch.");
1357 reason = "inbound event was dropped because of pending overdue app switch";
1358 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001359 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360 ALOGI("Dropped event because the current application is not responding and the user "
1361 "has started interacting with a different application.");
1362 reason = "inbound event was dropped because the current application is not responding "
1363 "and the user has started interacting with a different application";
1364 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001365 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001366 ALOGI("Dropped event because it is stale.");
1367 reason = "inbound event was dropped because it is stale";
1368 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001369 case DropReason::NO_POINTER_CAPTURE:
1370 ALOGI("Dropped event because there is no window with Pointer Capture.");
1371 reason = "inbound event was dropped because there is no window with Pointer Capture";
1372 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001373 case DropReason::NOT_DROPPED: {
1374 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001375 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001380 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001381 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001385 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001386 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1387 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001388 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 synthesizeCancelationEventsForAllConnectionsLocked(options);
1390 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001391 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1392 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393 synthesizeCancelationEventsForAllConnectionsLocked(options);
1394 }
1395 break;
1396 }
Chris Yef59a2f42020-10-16 12:55:26 -07001397 case EventEntry::Type::SENSOR: {
1398 break;
1399 }
arthurhungb89ccb02020-12-30 16:19:01 +08001400 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1401 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001402 break;
1403 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001404 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001405 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::CONFIGURATION_CHANGED:
1407 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001408 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001409 break;
1410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412}
1413
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001414static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1416 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417}
1418
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001419bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1420 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1421 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1422 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423}
1424
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001425bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001426 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427}
1428
1429void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001430 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001432 if (DEBUG_APP_SWITCH) {
1433 if (handled) {
1434 ALOGD("App switch has arrived.");
1435 } else {
1436 ALOGD("App switch was abandoned.");
1437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439}
1440
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001442 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443}
1444
Prabir Pradhancef936d2021-07-21 16:17:52 +00001445bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001446 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 return false;
1448 }
1449
1450 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001451 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001452 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001453 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1454 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001455 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 return true;
1457}
1458
Prabir Pradhancef936d2021-07-21 16:17:52 +00001459void InputDispatcher::postCommandLocked(Command&& command) {
1460 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461}
1462
1463void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001464 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001466 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 releaseInboundEventLocked(entry);
1468 }
1469 traceInboundQueueLengthLocked();
1470}
1471
1472void InputDispatcher::releasePendingEventLocked() {
1473 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001475 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 }
1477}
1478
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001479void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001481 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001482 if (DEBUG_DISPATCH_CYCLE) {
1483 ALOGD("Injected inbound event was dropped.");
1484 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001485 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 }
1487 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 }
1490 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491}
1492
1493void InputDispatcher::resetKeyRepeatLocked() {
1494 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001495 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497}
1498
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001499std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1500 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501
Michael Wright2e732952014-09-24 13:26:59 -07001502 uint32_t policyFlags = entry->policyFlags &
1503 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001505 std::shared_ptr<KeyEntry> newEntry =
1506 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1507 entry->source, entry->displayId, policyFlags, entry->action,
1508 entry->flags, entry->keyCode, entry->scanCode,
1509 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 newEntry->syntheticRepeat = true;
1512 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515}
1516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001517bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001519 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1520 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522
1523 // Reset key repeating in case a keyboard device was added or removed or something.
1524 resetKeyRepeatLocked();
1525
1526 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001527 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1528 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001529 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001530 };
1531 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533}
1534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1536 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001537 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1538 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1539 entry.deviceId);
1540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
liushenxiang42232912021-05-21 20:24:09 +08001542 // Reset key repeating in case a keyboard device was disabled or enabled.
1543 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1544 resetKeyRepeatLocked();
1545 }
1546
Michael Wrightfb04fd52022-11-24 22:31:11 +00001547 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001550
1551 // Remove all active pointers from this device
1552 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1553 touchState.removeAllPointersForDevice(entry.deviceId);
1554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 return true;
1556}
1557
Vishnu Nairad321cd2020-08-20 16:40:21 -07001558void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001559 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001560 if (mPendingEvent != nullptr) {
1561 // Move the pending event to the front of the queue. This will give the chance
1562 // for the pending event to get dispatched to the newly focused window
1563 mInboundQueue.push_front(mPendingEvent);
1564 mPendingEvent = nullptr;
1565 }
1566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001567 std::unique_ptr<FocusEntry> focusEntry =
1568 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1569 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001570
1571 // This event should go to the front of the queue, but behind all other focus events
1572 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001574 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 [](const std::shared_ptr<EventEntry>& event) {
1576 return event->type == EventEntry::Type::FOCUS;
1577 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001578
1579 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001581}
1582
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001583void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001584 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001585 if (channel == nullptr) {
1586 return; // Window has gone away
1587 }
1588 InputTarget target;
1589 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001590 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001591 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001592 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1593 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001594 std::string reason = std::string("reason=").append(entry->reason);
1595 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001596 dispatchEventLocked(currentTime, entry, {target});
1597}
1598
Prabir Pradhan99987712020-11-10 18:43:05 -08001599void InputDispatcher::dispatchPointerCaptureChangedLocked(
1600 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1601 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001602 dropReason = DropReason::NOT_DROPPED;
1603
Prabir Pradhan99987712020-11-10 18:43:05 -08001604 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001605 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001606
1607 if (entry->pointerCaptureRequest.enable) {
1608 // Enable Pointer Capture.
1609 if (haveWindowWithPointerCapture &&
1610 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001611 // This can happen if pointer capture is disabled and re-enabled before we notify the
1612 // app of the state change, so there is no need to notify the app.
1613 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1614 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001615 }
1616 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001617 // This can happen if a window requests capture and immediately releases capture.
1618 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001619 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001620 return;
1621 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001622 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1623 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1624 return;
1625 }
1626
Vishnu Nairc519ff72021-01-21 08:23:08 -08001627 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001628 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1629 mWindowTokenWithPointerCapture = token;
1630 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001631 // Disable Pointer Capture.
1632 // We do not check if the sequence number matches for requests to disable Pointer Capture
1633 // for two reasons:
1634 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1635 // to disable capture with the same sequence number: one generated by
1636 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1637 // Capture being disabled in InputReader.
1638 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1639 // actual Pointer Capture state that affects events being generated by input devices is
1640 // in InputReader.
1641 if (!haveWindowWithPointerCapture) {
1642 // Pointer capture was already forcefully disabled because of focus change.
1643 dropReason = DropReason::NOT_DROPPED;
1644 return;
1645 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001646 token = mWindowTokenWithPointerCapture;
1647 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001648 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001649 setPointerCaptureLocked(false);
1650 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001651 }
1652
1653 auto channel = getInputChannelLocked(token);
1654 if (channel == nullptr) {
1655 // Window has gone away, clean up Pointer Capture state.
1656 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001657 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001658 setPointerCaptureLocked(false);
1659 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001660 return;
1661 }
1662 InputTarget target;
1663 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001664 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001665 entry->dispatchInProgress = true;
1666 dispatchEventLocked(currentTime, entry, {target});
1667
1668 dropReason = DropReason::NOT_DROPPED;
1669}
1670
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001671void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1672 const std::shared_ptr<TouchModeEntry>& entry) {
1673 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001674 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001675 if (windowHandles.empty()) {
1676 return;
1677 }
1678 const std::vector<InputTarget> inputTargets =
1679 getInputTargetsFromWindowHandlesLocked(windowHandles);
1680 if (inputTargets.empty()) {
1681 return;
1682 }
1683 entry->dispatchInProgress = true;
1684 dispatchEventLocked(currentTime, entry, inputTargets);
1685}
1686
1687std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1688 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1689 std::vector<InputTarget> inputTargets;
1690 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001691 const sp<IBinder>& token = handle->getToken();
1692 if (token == nullptr) {
1693 continue;
1694 }
1695 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1696 if (channel == nullptr) {
1697 continue; // Window has gone away
1698 }
1699 InputTarget target;
1700 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001701 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001702 inputTargets.push_back(target);
1703 }
1704 return inputTargets;
1705}
1706
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001707bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001708 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 if (!entry->dispatchInProgress) {
1711 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1712 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1713 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1714 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001715 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 // We have seen two identical key downs in a row which indicates that the device
1717 // driver is automatically generating key repeats itself. We take note of the
1718 // repeat here, but we disable our own next key repeat timer since it is clear that
1719 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001720 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1721 // Make sure we don't get key down from a different device. If a different
1722 // device Id has same key pressed down, the new device Id will replace the
1723 // current one to hold the key repeat with repeat count reset.
1724 // In the future when got a KEY_UP on the device id, drop it and do not
1725 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1727 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001728 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 } else {
1730 // Not a repeat. Save key down state in case we do see a repeat later.
1731 resetKeyRepeatLocked();
1732 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1733 }
1734 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001735 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1736 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001737 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001738 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001739 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1740 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 resetKeyRepeatLocked();
1743 }
1744
1745 if (entry->repeatCount == 1) {
1746 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1747 } else {
1748 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1749 }
1750
1751 entry->dispatchInProgress = true;
1752
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001753 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
1755
1756 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001757 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 if (currentTime < entry->interceptKeyWakeupTime) {
1759 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1760 *nextWakeupTime = entry->interceptKeyWakeupTime;
1761 }
1762 return false; // wait until next wakeup
1763 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001764 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 entry->interceptKeyWakeupTime = 0;
1766 }
1767
1768 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001769 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001771 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001772 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001773
1774 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1775 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1776 };
1777 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001778 // Poke user activity for keys not passed to user
1779 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 return false; // wait for the command to run
1781 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001782 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001784 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001785 if (*dropReason == DropReason::NOT_DROPPED) {
1786 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
1788 }
1789
1790 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001791 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001792 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1794 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001795 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001796 // Poke user activity for undispatched keys
1797 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return true;
1799 }
1800
1801 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001802 InputEventInjectionResult injectionResult;
1803 sp<WindowInfoHandle> focusedWindow =
1804 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1805 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 return false;
1808 }
1809
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001810 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return true;
1813 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001814 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1815
1816 std::vector<InputTarget> inputTargets;
1817 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001818 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001819 getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001821 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001822 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823
1824 // Dispatch the key.
1825 dispatchEventLocked(currentTime, entry, inputTargets);
1826 return true;
1827}
1828
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001830 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1831 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1832 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1833 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1834 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1835 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1836 entry.metaState, entry.repeatCount, entry.downTime);
1837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838}
1839
Prabir Pradhancef936d2021-07-21 16:17:52 +00001840void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1841 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001842 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001843 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1844 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1845 "source=0x%x, sensorType=%s",
1846 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001847 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001848 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001849 auto command = [this, entry]() REQUIRES(mLock) {
1850 scoped_unlock unlock(mLock);
1851
1852 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001853 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001854 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001855 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1856 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001857 };
1858 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001859}
1860
1861bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001862 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1863 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001864 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001865 }
Chris Yef59a2f42020-10-16 12:55:26 -07001866 { // acquire lock
1867 std::scoped_lock _l(mLock);
1868
1869 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1870 std::shared_ptr<EventEntry> entry = *it;
1871 if (entry->type == EventEntry::Type::SENSOR) {
1872 it = mInboundQueue.erase(it);
1873 releaseInboundEventLocked(entry);
1874 }
1875 }
1876 }
1877 return true;
1878}
1879
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001880bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001881 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001882 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001884 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 entry->dispatchInProgress = true;
1886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889
1890 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001891 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001892 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1894 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 return true;
1896 }
1897
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001898 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899
1900 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001901 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 if (isPointerEvent) {
1905 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001906
1907 if (mDragState &&
1908 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1909 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1910 pilferPointersLocked(mDragState->dragWindow->getToken());
1911 }
1912
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001913 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001914 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001915 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1916 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 } else {
1918 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001919 sp<WindowInfoHandle> focusedWindow =
1920 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1921 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1922 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1923 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001924 InputTarget::Flags::FOREGROUND |
1925 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001926 getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 return false;
1931 }
1932
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001933 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001934 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001935 return true;
1936 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001938 CancelationOptions::Mode mode(
1939 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1940 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001941 CancelationOptions options(mode, "input event injection failed");
1942 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 return true;
1944 }
1945
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001946 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001947 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948
1949 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 dispatchEventLocked(currentTime, entry, inputTargets);
1951 return true;
1952}
1953
chaviw98318de2021-05-19 16:45:23 -05001954void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001955 bool isExiting, const int32_t rawX,
1956 const int32_t rawY) {
1957 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001958 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001959 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1960 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001961
1962 enqueueInboundEventLocked(std::move(dragEntry));
1963}
1964
1965void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1966 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1967 if (channel == nullptr) {
1968 return; // Window has gone away
1969 }
1970 InputTarget target;
1971 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001972 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001973 entry->dispatchInProgress = true;
1974 dispatchEventLocked(currentTime, entry, {target});
1975}
1976
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001977void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001978 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001979 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001980 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001981 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001982 "metaState=0x%x, buttonState=0x%x,"
1983 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001984 prefix, entry.eventTime, entry.deviceId,
1985 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1986 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1987 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1988 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07001990 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001991 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001992 "x=%f, y=%f, pressure=%f, size=%f, "
1993 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1994 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001995 i, entry.pointerProperties[i].id,
1996 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001997 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1998 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1999 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2000 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2001 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2002 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2003 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2004 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2005 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008}
2009
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002010void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2011 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002012 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002013 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002014 if (DEBUG_DISPATCH_CYCLE) {
2015 ALOGD("dispatchEventToCurrentInputTargets");
2016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002018 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002019
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2021
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002022 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002024 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002025 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002026 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002027 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002028 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002030 if (DEBUG_FOCUS) {
2031 ALOGD("Dropping event delivery to target with channel '%s' because it "
2032 "is no longer registered with the input dispatcher.",
2033 inputTarget.inputChannel->getName().c_str());
2034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036 }
2037}
2038
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002039void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002040 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2041 // If the policy decides to close the app, we will get a channel removal event via
2042 // unregisterInputChannel, and will clean up the connection that way. We are already not
2043 // sending new pointers to the connection when it blocked, but focused events will continue to
2044 // pile up.
2045 ALOGW("Canceling events for %s because it is unresponsive",
2046 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002047 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002048 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 "application not responding");
2050 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 }
2052}
2053
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002054void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002055 if (DEBUG_FOCUS) {
2056 ALOGD("Resetting ANR timeouts.");
2057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058
2059 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002060 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002061 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062}
2063
Tiger Huang721e26f2018-07-24 22:26:19 +08002064/**
2065 * Get the display id that the given event should go to. If this event specifies a valid display id,
2066 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2067 * Focused display is the display that the user most recently interacted with.
2068 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002069int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002070 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002071 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002072 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002073 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2074 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075 break;
2076 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002077 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2079 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002080 break;
2081 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002082 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002083 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002084 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002085 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002086 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002087 case EventEntry::Type::SENSOR:
2088 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002089 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002090 return ADISPLAY_ID_NONE;
2091 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002092 }
2093 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2094}
2095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2097 const char* focusedWindowName) {
2098 if (mAnrTracker.empty()) {
2099 // already processed all events that we waited for
2100 mKeyIsWaitingForEventsTimeout = std::nullopt;
2101 return false;
2102 }
2103
2104 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2105 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002106 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002107 mKeyIsWaitingForEventsTimeout = currentTime +
2108 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2109 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 return true;
2111 }
2112
2113 // We still have pending events, and already started the timer
2114 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2115 return true; // Still waiting
2116 }
2117
2118 // Waited too long, and some connection still hasn't processed all motions
2119 // Just send the key to the focused window
2120 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2121 focusedWindowName);
2122 mKeyIsWaitingForEventsTimeout = std::nullopt;
2123 return false;
2124}
2125
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002126sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2127 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2128 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002129 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002130 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131
Tiger Huang721e26f2018-07-24 22:26:19 +08002132 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002133 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002134 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002135 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2136
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 // If there is no currently focused window and no focused application
2138 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2140 ALOGI("Dropping %s event because there is no focused window or focused application in "
2141 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002142 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002143 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 }
2145
Vishnu Nair062a8672021-09-03 16:07:44 -07002146 // Drop key events if requested by input feature
2147 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002148 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002149 }
2150
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2152 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2153 // start interacting with another application via touch (app switch). This code can be removed
2154 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2155 // an app is expected to have a focused window.
2156 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2157 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2158 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002159 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2160 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2161 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002163 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002164 ALOGW("Waiting because no window has focus but %s may eventually add a "
2165 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002166 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002167 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002168 outInjectionResult = InputEventInjectionResult::PENDING;
2169 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2171 // Already raised ANR. Drop the event
2172 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002173 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002174 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 } else {
2176 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 outInjectionResult = InputEventInjectionResult::PENDING;
2178 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 }
2180 }
2181
2182 // we have a valid, non-null focused window
2183 resetNoFocusedWindowTimeoutLocked();
2184
Prabir Pradhan5735a322022-04-11 17:23:34 +00002185 // Verify targeted injection.
2186 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2187 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2189 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 }
2191
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002192 if (focusedWindowHandle->getInfo()->inputConfig.test(
2193 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002194 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002195 outInjectionResult = InputEventInjectionResult::PENDING;
2196 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002197 }
2198
2199 // If the event is a key event, then we must wait for all previous events to
2200 // complete before delivering it because previous events may have the
2201 // side-effect of transferring focus to a different window and we want to
2202 // ensure that the following keys are sent to the new window.
2203 //
2204 // Suppose the user touches a button in a window then immediately presses "A".
2205 // If the button causes a pop-up window to appear then we want to ensure that
2206 // the "A" key is delivered to the new pop-up window. This is because users
2207 // often anticipate pending UI changes when typing on a keyboard.
2208 // To obtain this behavior, we must serialize key events with respect to all
2209 // prior input events.
2210 if (entry.type == EventEntry::Type::KEY) {
2211 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2212 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002213 outInjectionResult = InputEventInjectionResult::PENDING;
2214 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002218 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2219 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220}
2221
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002222/**
2223 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2224 * that are currently unresponsive.
2225 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002226std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2227 const std::vector<Monitor>& monitors) const {
2228 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002230 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002231 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002232 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002233 if (connection == nullptr) {
2234 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002235 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 return false;
2237 }
2238 if (!connection->responsive) {
2239 ALOGW("Unresponsive monitor %s will not get the new gesture",
2240 connection->inputChannel->getName().c_str());
2241 return false;
2242 }
2243 return true;
2244 });
2245 return responsiveMonitors;
2246}
2247
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002248std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002249 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002250 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002251 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002253 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 // For security reasons, we defer updating the touch state until we are sure that
2255 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002256 const int32_t displayId = entry.displayId;
2257 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002258 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259
2260 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002263 // Copy current touch state into tempTouchState.
2264 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2265 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002266 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2269 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002270 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002271 }
2272
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002273 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002274
2275 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2276 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2277 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002278 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2279 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002280 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002281 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2282 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002283 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2284 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2285 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002286 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002287
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002288 if (newGesture) {
2289 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002290 }
2291
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002292 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2293 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2294 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002297 if (isHoverAction) {
2298 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2299 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002300 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002301 }
2302
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2304 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002305 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002306 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002307 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002308 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2309 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002310 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002311 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002312 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002313
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002314 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002315 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002318 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002319 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002321 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002322 }
2323
Prabir Pradhan5735a322022-04-11 17:23:34 +00002324 // Verify targeted injection.
2325 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2326 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002327 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002328 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002329 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002330 }
2331
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002332 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002333 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002334 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2335 // New window supports splitting, but we should never split mouse events.
2336 isSplit = !isFromMouse;
2337 } else if (isSplit) {
2338 // New window does not support splitting but we have already split events.
2339 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002340 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2341 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 newTouchedWindowHandle = nullptr;
2343 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002344 } else {
2345 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002346 // be delivered to a new window which supports split touch. Pointers from a mouse device
2347 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002348 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 }
2350
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002351 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002352 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002354 // Process the foreground window first so that it is the first to receive the event.
2355 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 }
2357
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002358 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002359 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2360 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002361 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002362 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002363 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002364 }
2365
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002367 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 continue;
2369 }
2370
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002371 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002372 // The "windowHandle" is the target of this hovering pointer.
2373 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002374 }
2375
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002376 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002377 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002379 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2380 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002381 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002382 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383
2384 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002385 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386 }
2387 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002388 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002392
2393 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002394
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002395 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002396 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002397 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002398 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2399 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2400 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId,
2401 pointerIds,
2402 isDownOrPointerDown
2403 ? std::make_optional(entry.eventTime)
2404 : std::nullopt);
2405 // If this is the pointer going down and the touched window has a wallpaper
2406 // then also add the touched wallpaper windows so they are locked in for the
2407 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2408 // SCROLL because the wallpaper engine only supports touch events. We would need to
2409 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2410 // handle these events.
2411 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002412 windowHandle->getInfo()->inputConfig.test(
2413 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2414 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2415 if (wallpaper != nullptr) {
2416 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2417 InputTarget::Flags::WINDOW_IS_OBSCURED |
2418 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2419 InputTarget::Flags::DISPATCH_AS_IS;
2420 if (isSplit) {
2421 wallpaperFlags |= InputTarget::Flags::SPLIT;
2422 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002423 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2424 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002425 }
2426 }
2427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002429
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002430 // If a window is already pilfering some pointers, give it this new pointer as well and
2431 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2432 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002433 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002434 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2435 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002436 // This window is already pilfering some pointers, and this new pointer is also
2437 // going to it. Therefore, take over this pointer and don't give it to anyone
2438 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002439 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002440 }
2441 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002442
2443 // Restrict all pilfered pointers to the pilfering windows.
2444 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 } else {
2446 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2447
2448 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002449 if (!tempTouchState.isDown(entry.deviceId) &&
2450 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
2451 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2452 << " is not down or we previously "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002453 "dropped the pointer down event in display "
2454 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002455 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002456 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
2458
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002459 // If the pointer is not currently hovering, then ignore the event.
2460 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2461 const int32_t pointerId = entry.pointerProperties[0].id;
2462 if (oldState == nullptr ||
2463 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2464 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2465 "display "
2466 << displayId << ": " << entry.getDescription();
2467 outInjectionResult = InputEventInjectionResult::FAILED;
2468 return {};
2469 }
2470 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2471 }
2472
arthurhung6d4bed92021-03-17 11:59:33 +08002473 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002474
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002476 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002477 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002478 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002479 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002480 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002481 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002482 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002483 sp<WindowInfoHandle> newTouchedWindowHandle =
2484 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002485
Prabir Pradhan5735a322022-04-11 17:23:34 +00002486 // Verify targeted injection.
2487 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2488 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002489 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002490 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002491 }
2492
Vishnu Nair062a8672021-09-03 16:07:44 -07002493 // Drop touch events if requested by input feature
2494 if (newTouchedWindowHandle != nullptr &&
2495 shouldDropInput(entry, newTouchedWindowHandle)) {
2496 newTouchedWindowHandle = nullptr;
2497 }
2498
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002499 if (newTouchedWindowHandle != nullptr &&
2500 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002501 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002502 oldTouchedWindowHandle->getName().c_str(),
2503 newTouchedWindowHandle->getName().c_str(), displayId);
2504
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002506 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002507 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002508 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002509
2510 const TouchedWindow& touchedWindow =
2511 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002512 addPointerWindowTargetLocked(oldTouchedWindowHandle,
2513 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
2514 pointerIds,
2515 touchedWindow.getDownTimeInTarget(entry.deviceId),
2516 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517
2518 // Make a slippery entrance into the new window.
2519 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002520 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 }
2522
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002523 ftl::Flags<InputTarget::Flags> targetFlags =
2524 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002525 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002526 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002529 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 }
2531 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002532 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002533 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002534 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002537 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2538 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002539
2540 // Check if the wallpaper window should deliver the corresponding event.
2541 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002542 tempTouchState, entry.deviceId, pointerId, targets);
2543 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2544 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 }
2546 }
Arthur Hung96483742022-11-15 03:30:48 +00002547
2548 // Update the pointerIds for non-splittable when it received pointer down.
2549 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2550 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002551 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002552 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2553 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2554 // Ignore drag window for it should just track one pointer.
2555 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2556 continue;
2557 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002558 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2559 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2560 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002561 }
2562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002565 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002566 {
2567 std::vector<TouchedWindow> hoveringWindows =
2568 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2569 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002570 std::optional<InputTarget> target =
2571 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002572 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002573 if (!target) {
2574 continue;
2575 }
2576 // Hardcode to single hovering pointer for now.
2577 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2578 pointerIds.set(entry.pointerProperties[0].id);
2579 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2580 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583
Prabir Pradhan5735a322022-04-11 17:23:34 +00002584 // Ensure that all touched windows are valid for injection.
2585 if (entry.injectionState != nullptr) {
2586 std::string errs;
2587 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002588 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2589 if (err) errs += "\n - " + *err;
2590 }
2591 if (!errs.empty()) {
2592 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002593 "%s:%s",
2594 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002595 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002596 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002597 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002598 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002599
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002600 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2601 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002603 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002604 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002605 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002606 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002607 for (InputTarget& target : targets) {
2608 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2609 sp<WindowInfoHandle> targetWindow =
2610 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2611 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2612 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615 }
2616 }
2617 }
2618
Harry Cuttsb166c002023-05-09 13:06:05 +00002619 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2620 // only want the system UI to handle these gestures.
2621 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2622 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2623 if (isTouchpadNavGesture) {
2624 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2625 }
2626
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002627 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002628 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002629 std::bitset<MAX_POINTER_ID + 1> touchingPointers =
2630 touchedWindow.getTouchingPointers(entry.deviceId);
2631 if (touchingPointers.none()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002632 continue;
2633 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002634 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2635 touchingPointers,
2636 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002637 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002638
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002639 // During targeted injection, only allow owned targets to receive events
2640 std::erase_if(targets, [&](const InputTarget& target) {
2641 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2642 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2643 if (err) {
2644 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2645 << ": " << (*err);
2646 return true;
2647 }
2648 return false;
2649 });
2650
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002651 if (targets.empty()) {
2652 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2653 outInjectionResult = InputEventInjectionResult::FAILED;
2654 return {};
2655 }
2656
2657 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2658 // window that is actually receiving the entire gesture.
2659 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2660 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2661 })) {
2662 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2663 << entry.getDescription();
2664 outInjectionResult = InputEventInjectionResult::FAILED;
2665 return {};
2666 }
2667
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002668 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002670 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2671 // Targets that we entered in a slippery way will now become AS-IS targets
2672 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
2673 touchedWindow.targetFlags.clear(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
2674 touchedWindow.targetFlags |= InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002675 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002676 }
2677
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002678 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002679 if (isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002680 if (oldState && oldState->isDown(entry.deviceId)) {
2681 // Started hovering, but the device is already down: reject the hover event
2682 LOG(ERROR) << "Got hover event " << entry.getDescription()
2683 << " but the device is already down " << oldState->dump();
2684 outInjectionResult = InputEventInjectionResult::FAILED;
2685 return {};
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002686 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002687 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2688 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002689 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002690 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002691 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002692 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002693 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2694 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002695 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2696 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2697 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
2699
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002700 // Save changes unless the action was scroll in which case the temporary touch
2701 // state was only valid for this one action.
2702 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002703 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002704 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 mTouchStatesByDisplay[displayId] = tempTouchState;
2706 } else {
2707 mTouchStatesByDisplay.erase(displayId);
2708 }
2709 }
2710
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002711 if (tempTouchState.windows.empty()) {
2712 mTouchStatesByDisplay.erase(displayId);
2713 }
2714
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002715 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716}
2717
arthurhung6d4bed92021-03-17 11:59:33 +08002718void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002719 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2720 // have an explicit reason to support it.
2721 constexpr bool isStylus = false;
2722
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002723 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002724 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002725 if (dropWindow) {
2726 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002727 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002728 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002729 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002730 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002731 }
2732 mDragState.reset();
2733}
2734
2735void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002736 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002737 return;
2738 }
2739
arthurhung6d4bed92021-03-17 11:59:33 +08002740 if (!mDragState->isStartDrag) {
2741 mDragState->isStartDrag = true;
2742 mDragState->isStylusButtonDownAtStart =
2743 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2744 }
2745
Arthur Hung54745652022-04-20 07:17:41 +00002746 // Find the pointer index by id.
2747 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002748 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002749 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2750 if (pointerProperties.id == mDragState->pointerId) {
2751 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002752 }
Arthur Hung54745652022-04-20 07:17:41 +00002753 }
arthurhung6d4bed92021-03-17 11:59:33 +08002754
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002755 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002756 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002757 }
2758
2759 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2760 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2761 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2762
2763 switch (maskedAction) {
2764 case AMOTION_EVENT_ACTION_MOVE: {
2765 // Handle the special case : stylus button no longer pressed.
2766 bool isStylusButtonDown =
2767 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2768 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2769 finishDragAndDrop(entry.displayId, x, y);
2770 return;
2771 }
2772
2773 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2774 // until we have an explicit reason to support it.
2775 constexpr bool isStylus = false;
2776
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002777 sp<WindowInfoHandle> hoverWindowHandle =
2778 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2779 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002780 // enqueue drag exit if needed.
2781 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2782 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2783 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002784 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002785 y);
2786 }
2787 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2788 }
2789 // enqueue drag location if needed.
2790 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002791 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002792 }
2793 break;
2794 }
2795
2796 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002797 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002798 break;
2799 }
2800 // The drag pointer is up.
2801 [[fallthrough]];
2802 case AMOTION_EVENT_ACTION_UP:
2803 finishDragAndDrop(entry.displayId, x, y);
2804 break;
2805 case AMOTION_EVENT_ACTION_CANCEL: {
2806 ALOGD("Receiving cancel when drag and drop.");
2807 sendDropWindowCommandLocked(nullptr, 0, 0);
2808 mDragState.reset();
2809 break;
2810 }
arthurhungb89ccb02020-12-30 16:19:01 +08002811 }
2812}
2813
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002814std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2815 const sp<android::gui::WindowInfoHandle>& windowHandle,
2816 ftl::Flags<InputTarget::Flags> targetFlags,
2817 std::optional<nsecs_t> firstDownTimeInTarget) const {
2818 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2819 if (inputChannel == nullptr) {
2820 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2821 return {};
2822 }
2823 InputTarget inputTarget;
2824 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002825 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002826 inputTarget.flags = targetFlags;
2827 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2828 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2829 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2830 if (displayInfoIt != mDisplayInfos.end()) {
2831 inputTarget.displayTransform = displayInfoIt->second.transform;
2832 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002833 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002834 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2835 }
2836 return inputTarget;
2837}
2838
chaviw98318de2021-05-19 16:45:23 -05002839void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002840 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002841 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002842 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002843 std::vector<InputTarget>::iterator it =
2844 std::find_if(inputTargets.begin(), inputTargets.end(),
2845 [&windowHandle](const InputTarget& inputTarget) {
2846 return inputTarget.inputChannel->getConnectionToken() ==
2847 windowHandle->getToken();
2848 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002849
chaviw98318de2021-05-19 16:45:23 -05002850 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002851
2852 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002853 std::optional<InputTarget> target =
2854 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2855 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002856 return;
2857 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002859 it = inputTargets.end() - 1;
2860 }
2861
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002862 if (it->flags != targetFlags) {
2863 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2864 }
2865 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2866 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2867 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2868 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002869}
2870
2871void InputDispatcher::addPointerWindowTargetLocked(
2872 const sp<android::gui::WindowInfoHandle>& windowHandle,
2873 ftl::Flags<InputTarget::Flags> targetFlags, std::bitset<MAX_POINTER_ID + 1> pointerIds,
2874 std::optional<nsecs_t> firstDownTimeInTarget, std::vector<InputTarget>& inputTargets) const
2875 REQUIRES(mLock) {
2876 if (pointerIds.none()) {
2877 for (const auto& target : inputTargets) {
2878 LOG(INFO) << "Target: " << target;
2879 }
2880 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2881 return;
2882 }
2883 std::vector<InputTarget>::iterator it =
2884 std::find_if(inputTargets.begin(), inputTargets.end(),
2885 [&windowHandle](const InputTarget& inputTarget) {
2886 return inputTarget.inputChannel->getConnectionToken() ==
2887 windowHandle->getToken();
2888 });
2889
2890 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2891 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2892 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2893 // input targets for hovering pointers and for touching pointers.
2894 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2895 // target instead.
2896 if (it != inputTargets.end() && it->flags.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
2897 // Force the code below to create a new input target
2898 it = inputTargets.end();
2899 }
2900
2901 const WindowInfo* windowInfo = windowHandle->getInfo();
2902
2903 if (it == inputTargets.end()) {
2904 std::optional<InputTarget> target =
2905 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2906 if (!target) {
2907 return;
2908 }
2909 inputTargets.push_back(*target);
2910 it = inputTargets.end() - 1;
2911 }
2912
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002913 if (it->flags != targetFlags) {
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002914 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002915 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002916 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2917 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2918 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2919 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002920
chaviw1ff3d1e2020-07-01 15:53:47 -07002921 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922}
2923
Michael Wright3dd60e22019-03-27 22:06:44 +00002924void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002925 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002926 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2927 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002928
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002929 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2930 InputTarget target;
2931 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002932 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002933 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2934 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002935 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2936 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002937 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002938 target.setDefaultPointerTransform(target.displayTransform);
2939 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 }
2941}
2942
Robert Carrc9bf1d32020-04-13 17:21:08 -07002943/**
2944 * Indicate whether one window handle should be considered as obscuring
2945 * another window handle. We only check a few preconditions. Actually
2946 * checking the bounds is left to the caller.
2947 */
chaviw98318de2021-05-19 16:45:23 -05002948static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2949 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002950 // Compare by token so cloned layers aren't counted
2951 if (haveSameToken(windowHandle, otherHandle)) {
2952 return false;
2953 }
2954 auto info = windowHandle->getInfo();
2955 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002956 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002957 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002958 } else if (otherInfo->alpha == 0 &&
2959 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002960 // Those act as if they were invisible, so we don't need to flag them.
2961 // We do want to potentially flag touchable windows even if they have 0
2962 // opacity, since they can consume touches and alter the effects of the
2963 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002964 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002965 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2966 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002967 } else if (info->ownerUid == otherInfo->ownerUid) {
2968 // If ownerUid is the same we don't generate occlusion events as there
2969 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002970 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002971 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002972 return false;
2973 } else if (otherInfo->displayId != info->displayId) {
2974 return false;
2975 }
2976 return true;
2977}
2978
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002979/**
2980 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2981 * untrusted, one should check:
2982 *
2983 * 1. If result.hasBlockingOcclusion is true.
2984 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2985 * BLOCK_UNTRUSTED.
2986 *
2987 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2988 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2989 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2990 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2991 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2992 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2993 *
2994 * If neither of those is true, then it means the touch can be allowed.
2995 */
2996InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002997 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2998 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002999 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003000 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003001 TouchOcclusionInfo info;
3002 info.hasBlockingOcclusion = false;
3003 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003004 info.obscuringUid = gui::Uid::INVALID;
3005 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003006 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003007 if (windowHandle == otherHandle) {
3008 break; // All future windows are below us. Exit early.
3009 }
chaviw98318de2021-05-19 16:45:23 -05003010 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003011 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3012 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003013 if (DEBUG_TOUCH_OCCLUSION) {
3014 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003015 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003016 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003017 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3018 // we perform the checks below to see if the touch can be propagated or not based on the
3019 // window's touch occlusion mode
3020 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3021 info.hasBlockingOcclusion = true;
3022 info.obscuringUid = otherInfo->ownerUid;
3023 info.obscuringPackage = otherInfo->packageName;
3024 break;
3025 }
3026 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003027 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003028 float opacity =
3029 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3030 // Given windows A and B:
3031 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3032 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3033 opacityByUid[uid] = opacity;
3034 if (opacity > info.obscuringOpacity) {
3035 info.obscuringOpacity = opacity;
3036 info.obscuringUid = uid;
3037 info.obscuringPackage = otherInfo->packageName;
3038 }
3039 }
3040 }
3041 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003042 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003043 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003044 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003045 return info;
3046}
3047
chaviw98318de2021-05-19 16:45:23 -05003048std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003049 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003050 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003051 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3052 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3053 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003054 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003055 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003056 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3057 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003058 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3059 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3060 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003061 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003062}
3063
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003064bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3065 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003066 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3067 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003068 return false;
3069 }
3070 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003071 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003072 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003073 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003074 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3075 return false;
3076 }
3077 return true;
3078}
3079
chaviw98318de2021-05-19 16:45:23 -05003080bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003083 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3084 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003085 if (windowHandle == otherHandle) {
3086 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 }
chaviw98318de2021-05-19 16:45:23 -05003088 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003089 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003090 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 return true;
3092 }
3093 }
3094 return false;
3095}
3096
chaviw98318de2021-05-19 16:45:23 -05003097bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003098 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003099 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3100 const WindowInfo* windowInfo = windowHandle->getInfo();
3101 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003102 if (windowHandle == otherHandle) {
3103 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003104 }
chaviw98318de2021-05-19 16:45:23 -05003105 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003106 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003107 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003108 return true;
3109 }
3110 }
3111 return false;
3112}
3113
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003114std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003115 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003116 if (applicationHandle != nullptr) {
3117 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003118 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 } else {
3120 return applicationHandle->getName();
3121 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003122 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003123 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003125 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 }
3127}
3128
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003129void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003130 if (!isUserActivityEvent(eventEntry)) {
3131 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003132 return;
3133 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003134 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003135 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003136 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003137 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003138 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003139 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003140 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 }
3142 }
3143
3144 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003145 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3148 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 return;
3150 }
Josep del Riob3981622023-04-18 15:49:45 +00003151 if (windowDisablingUserActivityInfo != nullptr) {
3152 if (DEBUG_DISPATCH_CYCLE) {
3153 ALOGD("Not poking user activity: disabled by window '%s'.",
3154 windowDisablingUserActivityInfo->name.c_str());
3155 }
3156 return;
3157 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003158 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 eventType = USER_ACTIVITY_EVENT_TOUCH;
3160 }
3161 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003163 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003164 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3165 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 return;
3167 }
Josep del Riob3981622023-04-18 15:49:45 +00003168 // If the key code is unknown, we don't consider it user activity
3169 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3170 return;
3171 }
3172 // Don't inhibit events that were intercepted or are not passed to
3173 // the apps, like system shortcuts
3174 if (windowDisablingUserActivityInfo != nullptr &&
3175 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3176 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3177 if (DEBUG_DISPATCH_CYCLE) {
3178 ALOGD("Not poking user activity: disabled by window '%s'.",
3179 windowDisablingUserActivityInfo->name.c_str());
3180 }
3181 return;
3182 }
3183
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 eventType = USER_ACTIVITY_EVENT_BUTTON;
3185 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003187 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003188 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003189 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003190 break;
3191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 }
3193
Prabir Pradhancef936d2021-07-21 16:17:52 +00003194 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3195 REQUIRES(mLock) {
3196 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003197 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003198 };
3199 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200}
3201
3202void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003203 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003205 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003206 ATRACE_NAME_IF(ATRACE_ENABLED(),
3207 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3208 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003209 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003210 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003211 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003212 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003213 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003214 inputTarget.getPointerInfoString().c_str());
3215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216
3217 // Skip this event if the connection status is not normal.
3218 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003219 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003220 if (DEBUG_DISPATCH_CYCLE) {
3221 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003222 connection->getInputChannelName().c_str(),
3223 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 return;
3226 }
3227
3228 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003229 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003230 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003231 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003232 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003234 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003235 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003236 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3237 logDispatchStateLocked();
3238 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3239 "target on connection "
3240 << connection->getInputChannelName() << " for "
3241 << originalMotionEntry.getDescription();
3242 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003243 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003244 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3245 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 if (!splitMotionEntry) {
3247 return; // split event was dropped
3248 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003249 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3250 std::string reason = std::string("reason=pointer cancel on split window");
3251 android_log_event_list(LOGTAG_INPUT_CANCEL)
3252 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3253 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003254 if (DEBUG_FOCUS) {
3255 ALOGD("channel '%s' ~ Split motion event.",
3256 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003257 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003258 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003259 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3260 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 return;
3262 }
3263 }
3264
3265 // Not splitting. Enqueue dispatch entries for the event as is.
3266 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3267}
3268
3269void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003270 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003271 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003272 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003273 ATRACE_NAME_IF(ATRACE_ENABLED(),
3274 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3275 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003276 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3277 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003278
hongzuo liu95785e22022-09-06 02:51:35 +00003279 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280
3281 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003283 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003287 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003289 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003291 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294
3295 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003296 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 startDispatchCycleLocked(currentTime, connection);
3298 }
3299}
3300
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003301void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003302 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003303 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003304 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003305 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3306 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 return;
3308 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003309
3310 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3311 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
3313 // This is a new event.
3314 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003315 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003316 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003318 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3319 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003320 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003322 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003323 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3326 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003327 LOG(WARNING) << "channel " << connection->getInputChannelName()
3328 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 return; // skip the inconsistent event
3330 }
3331 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003334 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003335 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003336 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3337 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3338 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3339 static_cast<int32_t>(IdGenerator::Source::OTHER);
3340 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003341 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003343 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003345 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003347 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003349 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3351 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003352 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 }
3354 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003355 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3356 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003357 if (DEBUG_DISPATCH_CYCLE) {
3358 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3359 "enter event",
3360 connection->getInputChannelName().c_str());
3361 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003362 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3363 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003367 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3368 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3369 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003370 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003371 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3372 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003373 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003377 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3378 // devices being active at the same time in the same window, so if a new device is
3379 // active, cancel the gesture from the old device.
3380
3381 std::unique_ptr<EventEntry> cancelEvent =
3382 connection->inputState
3383 .cancelConflictingInputStream(motionEntry,
3384 dispatchEntry->resolvedAction);
3385 if (cancelEvent != nullptr) {
3386 LOG(INFO) << "Canceling pointers for device " << motionEntry.deviceId << " in "
3387 << connection->getInputChannelName() << " with event "
3388 << cancelEvent->getDescription();
3389 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3390 createDispatchEntry(inputTarget, std::move(cancelEvent),
3391 InputTarget::Flags::DISPATCH_AS_IS);
3392
3393 // Send these cancel events to the queue before sending the event from the new
3394 // device.
3395 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3396 }
3397
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3399 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003400 LOG(WARNING) << "channel " << connection->getInputChannelName()
3401 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003402 return; // skip the inconsistent event
3403 }
3404
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003405 dispatchEntry->resolvedEventId =
3406 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3407 ? mIdGenerator.nextId()
3408 : motionEntry.id;
3409 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3410 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3411 ") to MotionEvent(id=0x%" PRIx32 ").",
3412 motionEntry.id, dispatchEntry->resolvedEventId);
3413 ATRACE_NAME(message.c_str());
3414 }
3415
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003416 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3417 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3418 // Skip reporting pointer down outside focus to the policy.
3419 break;
3420 }
3421
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003422 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003423 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003424
3425 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003427 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003428 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003429 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3430 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003431 break;
3432 }
Chris Yef59a2f42020-10-16 12:55:26 -07003433 case EventEntry::Type::SENSOR: {
3434 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3435 break;
3436 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003437 case EventEntry::Type::CONFIGURATION_CHANGED:
3438 case EventEntry::Type::DEVICE_RESET: {
3439 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003440 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003441 break;
3442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
3444
3445 // Remember that we are waiting for this dispatch to complete.
3446 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003447 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449
3450 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003451 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003452 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003453}
3454
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003455/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003457 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003458 * The first role is to log input interaction with windows, which helps determine what the user was
3459 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3460 * that user started interacting with launcher window, as well as any other window that received
3461 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3462 * when the set of tokens that received the event changes. It is not logged again as long as the
3463 * user is interacting with the same windows.
3464 *
3465 * The second role is to track input device activity for metrics collection. For each input event,
3466 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3467 * input_interaction logs, the device interaction is reported even when the set of interaction
3468 * tokens do not change.
3469 *
3470 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3471 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003472 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003473void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3474 const std::vector<InputTarget>& targets) {
3475 int32_t deviceId;
3476 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003477 // Skip ACTION_UP events, and all events other than keys and motions
3478 if (entry.type == EventEntry::Type::KEY) {
3479 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3480 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3481 return;
3482 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003483 deviceId = keyEntry.deviceId;
3484 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003485 } else if (entry.type == EventEntry::Type::MOTION) {
3486 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3487 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003488 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3489 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 return;
3491 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003492 deviceId = motionEntry.deviceId;
3493 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003494 } else {
3495 return; // Not a key or a motion
3496 }
3497
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003498 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003499 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003500 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003501 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003502 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003503 continue; // Skip windows that receive ACTION_OUTSIDE
3504 }
3505
3506 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003507 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003508 if (connection == nullptr) {
3509 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003510 }
3511 newConnectionTokens.insert(std::move(token));
3512 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003513 if (target.windowHandle) {
3514 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3515 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003516 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003517
3518 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3519 REQUIRES(mLock) {
3520 scoped_unlock unlock(mLock);
3521 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3522 };
3523 postCommandLocked(std::move(command));
3524
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003525 if (newConnectionTokens == mInteractionConnectionTokens) {
3526 return; // no change
3527 }
3528 mInteractionConnectionTokens = newConnectionTokens;
3529
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003530 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003531 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003532 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003533 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003534 std::string message = "Interaction with: " + targetList;
3535 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003536 message += "<none>";
3537 }
3538 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3539}
3540
chaviwfd6d3512019-03-25 13:23:49 -07003541void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003542 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003543 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003544 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3545 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003546 return;
3547 }
3548
Vishnu Nairc519ff72021-01-21 08:23:08 -08003549 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003550 if (focusedToken == token) {
3551 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003552 return;
3553 }
3554
Prabir Pradhancef936d2021-07-21 16:17:52 +00003555 auto command = [this, token]() REQUIRES(mLock) {
3556 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003557 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003558 };
3559 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560}
3561
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003562status_t InputDispatcher::publishMotionEvent(Connection& connection,
3563 DispatchEntry& dispatchEntry) const {
3564 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3565 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3566
3567 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003568 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003569
3570 // Set the X and Y offset and X and Y scale depending on the input source.
3571 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003572 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003573 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3574 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003575 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003576 scaledCoords[i] = motionEntry.pointerCoords[i];
3577 // Don't apply window scale here since we don't want scale to affect raw
3578 // coordinates. The scale will be sent back to the client and applied
3579 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003580 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003581 }
3582 usingCoords = scaledCoords;
3583 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003584 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003585 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003586 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003587 scaledCoords[i].clear();
3588 }
3589 usingCoords = scaledCoords;
3590 }
3591
3592 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3593
3594 // Publish the motion event.
3595 return connection.inputPublisher
3596 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3597 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3598 std::move(hmac), dispatchEntry.resolvedAction,
3599 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3600 motionEntry.edgeFlags, motionEntry.metaState,
3601 motionEntry.buttonState, motionEntry.classification,
3602 dispatchEntry.transform, motionEntry.xPrecision,
3603 motionEntry.yPrecision, motionEntry.xCursorPosition,
3604 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3605 motionEntry.downTime, motionEntry.eventTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003606 motionEntry.getPointerCount(), motionEntry.pointerProperties.data(),
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003607 usingCoords);
3608}
3609
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003611 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003612 ATRACE_NAME_IF(ATRACE_ENABLED(),
3613 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3614 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003615 if (DEBUG_DISPATCH_CYCLE) {
3616 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003619 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003620 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003622 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003623 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624
3625 // Publish the event.
3626 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003627 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3628 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003629 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3631 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003632 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003633 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3634 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003638 status = connection->inputPublisher
3639 .publishKeyEvent(dispatchEntry->seq,
3640 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3641 keyEntry.source, keyEntry.displayId,
3642 std::move(hmac), dispatchEntry->resolvedAction,
3643 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3644 keyEntry.scanCode, keyEntry.metaState,
3645 keyEntry.repeatCount, keyEntry.downTime,
3646 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
3649
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003650 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003651 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003652 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3653 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003654 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003655 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003656 break;
3657 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003658
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003659 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003661 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003663 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003664 break;
3665 }
3666
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003667 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3668 const TouchModeEntry& touchModeEntry =
3669 static_cast<const TouchModeEntry&>(eventEntry);
3670 status = connection->inputPublisher
3671 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3672 touchModeEntry.inTouchMode);
3673
3674 break;
3675 }
3676
Prabir Pradhan99987712020-11-10 18:43:05 -08003677 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3678 const auto& captureEntry =
3679 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3680 status = connection->inputPublisher
3681 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003682 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003683 break;
3684 }
3685
arthurhungb89ccb02020-12-30 16:19:01 +08003686 case EventEntry::Type::DRAG: {
3687 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3688 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3689 dragEntry.id, dragEntry.x,
3690 dragEntry.y,
3691 dragEntry.isExiting);
3692 break;
3693 }
3694
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003695 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003696 case EventEntry::Type::DEVICE_RESET:
3697 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003698 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003699 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003700 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 }
3703
3704 // Check the result.
3705 if (status) {
3706 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003707 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003709 "This is unexpected because the wait queue is empty, so the pipe "
3710 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003711 "event to it, status=%s(%d)",
3712 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3713 status);
Harry Cutts33476232023-01-30 19:57:29 +00003714 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 } else {
3716 // Pipe is full and we are waiting for the app to finish process some events
3717 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003718 if (DEBUG_DISPATCH_CYCLE) {
3719 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3720 "waiting for the application to catch up",
3721 connection->getInputChannelName().c_str());
3722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 }
3724 } else {
3725 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003726 "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 }
3731 return;
3732 }
3733
3734 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003735 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3736 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3737 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003738 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003739 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003740 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003741 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003742 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 }
3744}
3745
chaviw09c8d2d2020-08-24 15:48:26 -07003746std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3747 size_t size;
3748 switch (event.type) {
3749 case VerifiedInputEvent::Type::KEY: {
3750 size = sizeof(VerifiedKeyEvent);
3751 break;
3752 }
3753 case VerifiedInputEvent::Type::MOTION: {
3754 size = sizeof(VerifiedMotionEvent);
3755 break;
3756 }
3757 }
3758 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3759 return mHmacKeyManager.sign(start, size);
3760}
3761
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003762const std::array<uint8_t, 32> InputDispatcher::getSignature(
3763 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003764 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003765 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003766 // Only sign events up and down events as the purely move events
3767 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003768 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003769 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003770
3771 VerifiedMotionEvent verifiedEvent =
3772 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3773 verifiedEvent.actionMasked = actionMasked;
3774 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3775 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003776}
3777
3778const std::array<uint8_t, 32> InputDispatcher::getSignature(
3779 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3780 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3781 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3782 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003783 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003784}
3785
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003787 const std::shared_ptr<Connection>& connection,
3788 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003789 if (DEBUG_DISPATCH_CYCLE) {
3790 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3791 connection->getInputChannelName().c_str(), seq, toString(handled));
3792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003794 if (connection->status == Connection::Status::BROKEN ||
3795 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 return;
3797 }
3798
3799 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003800 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3801 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3802 };
3803 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804}
3805
3806void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003807 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003808 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003809 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003810 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3811 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813
3814 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003815 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003816 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003817 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003818 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819
3820 // The connection appears to be unrecoverably broken.
3821 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003822 if (connection->status == Connection::Status::NORMAL) {
3823 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824
3825 if (notify) {
3826 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003827 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3828 connection->getInputChannelName().c_str());
3829
3830 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003831 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003832 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003833 };
3834 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836 }
3837}
3838
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003839void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003840 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003841 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003842 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 }
3844}
3845
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003846void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003848 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850}
3851
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003852int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3853 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003854 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003855 if (connection == nullptr) {
3856 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3857 connectionToken.get(), events);
3858 return 0; // remove the callback
3859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003861 bool notify;
3862 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3863 if (!(events & ALOOPER_EVENT_INPUT)) {
3864 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3865 "events=0x%x",
3866 connection->getInputChannelName().c_str(), events);
3867 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 }
3869
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003870 nsecs_t currentTime = now();
3871 bool gotOne = false;
3872 status_t status = OK;
3873 for (;;) {
3874 Result<InputPublisher::ConsumerResponse> result =
3875 connection->inputPublisher.receiveConsumerResponse();
3876 if (!result.ok()) {
3877 status = result.error().code();
3878 break;
3879 }
3880
3881 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3882 const InputPublisher::Finished& finish =
3883 std::get<InputPublisher::Finished>(*result);
3884 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3885 finish.consumeTime);
3886 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003887 if (shouldReportMetricsForConnection(*connection)) {
3888 const InputPublisher::Timeline& timeline =
3889 std::get<InputPublisher::Timeline>(*result);
3890 mLatencyTracker
3891 .trackGraphicsLatency(timeline.inputEventId,
3892 connection->inputChannel->getConnectionToken(),
3893 std::move(timeline.graphicsTimeline));
3894 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003895 }
3896 gotOne = true;
3897 }
3898 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003899 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003900 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 return 1;
3902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 }
3904
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003905 notify = status != DEAD_OBJECT || !connection->monitor;
3906 if (notify) {
3907 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3908 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3909 status);
3910 }
3911 } else {
3912 // Monitor channels are never explicitly unregistered.
3913 // We do it automatically when the remote endpoint is closed so don't warn about them.
3914 const bool stillHaveWindowHandle =
3915 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3916 notify = !connection->monitor && stillHaveWindowHandle;
3917 if (notify) {
3918 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3919 connection->getInputChannelName().c_str(), events);
3920 }
3921 }
3922
3923 // Remove the channel.
3924 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3925 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926}
3927
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003928void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003930 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003931 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 }
3933}
3934
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003935void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003936 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003937 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003938 for (const Monitor& monitor : monitors) {
3939 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003940 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003941 }
3942}
3943
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003945 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003946 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003947 if (connection == nullptr) {
3948 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003950
3951 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952}
3953
3954void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003955 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li5af92f92023-07-14 14:36:22 +08003956 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3957 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3958 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3959 LOG(INFO) << __func__
3960 << ": Canceling drag and drop because the pointers for the drag window are being "
3961 "canceled.";
3962 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3963 mDragState.reset();
3964 }
3965
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003966 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 return;
3968 }
3969
3970 nsecs_t currentTime = now();
3971
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003972 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003973 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003975 if (cancelationEvents.empty()) {
3976 return;
3977 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003978 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3979 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003980 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003981 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003982 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003983 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003984
Arthur Hungb3307ee2021-10-14 10:57:37 +00003985 std::string reason = std::string("reason=").append(options.reason);
3986 android_log_event_list(LOGTAG_INPUT_CANCEL)
3987 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3988
hongzuo liu95785e22022-09-06 02:51:35 +00003989 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003990 // The target to use if we don't find a window associated with the channel.
3991 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3992 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3993 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003994
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003995 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003996 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003997 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003998
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003999 switch (cancelationEventEntry->type) {
4000 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004001 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004002 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4003 ? std::make_optional(keyEntry.displayId)
4004 : std::nullopt;
4005 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
4006 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004007 keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004008 } else {
4009 targets.emplace_back(fallbackTarget);
4010 }
4011 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004012 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004014 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004015 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004016 const std::optional<int32_t> targetDisplay =
4017 motionEntry.displayId != ADISPLAY_ID_NONE
4018 ? std::make_optional(motionEntry.displayId)
4019 : std::nullopt;
4020 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004021 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004022 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004023 pointerIndex++) {
4024 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4025 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004026 addPointerWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
4027 pointerIds, motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004028 } else {
4029 targets.emplace_back(fallbackTarget);
4030 const auto it = mDisplayInfos.find(motionEntry.displayId);
4031 if (it != mDisplayInfos.end()) {
4032 targets.back().displayTransform = it->second.transform;
4033 targets.back().setDefaultPointerTransform(it->second.transform);
4034 }
4035 }
4036 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004037 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004039 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004040 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004041 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4042 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004043 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004044 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004045 break;
4046 }
4047 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004048 case EventEntry::Type::DEVICE_RESET:
4049 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004050 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004051 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004052 break;
4053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 }
4055
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004056 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4057 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004058 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004060
hongzuo liu95785e22022-09-06 02:51:35 +00004061 // If the outbound queue was previously empty, start the dispatch cycle going.
4062 if (wasEmpty && !connection->outboundQueue.empty()) {
4063 startDispatchCycleLocked(currentTime, connection);
4064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065}
4066
Svet Ganov5d3bc372020-01-26 23:11:07 -08004067void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004068 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004069 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004070 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004071 return;
4072 }
4073
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004074 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004075 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004076
4077 if (downEvents.empty()) {
4078 return;
4079 }
4080
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004081 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004082 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4083 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004084 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004085
chaviw98318de2021-05-19 16:45:23 -05004086 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004087 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004088
hongzuo liu95785e22022-09-06 02:51:35 +00004089 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004090 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004091 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004092 switch (downEventEntry->type) {
4093 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004094 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4095 if (windowHandle != nullptr) {
4096 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004097 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004098 pointerIndex++) {
4099 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4100 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004101 addPointerWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4102 motionEntry.downTime, targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004103 } else {
4104 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4105 .flags = targetFlags});
4106 const auto it = mDisplayInfos.find(motionEntry.displayId);
4107 if (it != mDisplayInfos.end()) {
4108 targets.back().displayTransform = it->second.transform;
4109 targets.back().setDefaultPointerTransform(it->second.transform);
4110 }
4111 }
4112 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004113 break;
4114 }
4115
4116 case EventEntry::Type::KEY:
4117 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004118 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004119 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004120 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004121 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004122 case EventEntry::Type::SENSOR:
4123 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004124 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004125 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004126 break;
4127 }
4128 }
4129
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004130 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4131 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004132 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004133 }
4134
hongzuo liu95785e22022-09-06 02:51:35 +00004135 // If the outbound queue was previously empty, start the dispatch cycle going.
4136 if (wasEmpty && !connection->outboundQueue.empty()) {
4137 startDispatchCycleLocked(downTime, connection);
4138 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004139}
4140
Arthur Hungc539dbb2022-12-08 07:45:36 +00004141void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4142 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4143 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004144 std::shared_ptr<Connection> wallpaperConnection =
4145 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004146 if (wallpaperConnection != nullptr) {
4147 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4148 }
4149 }
4150}
4151
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004152std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004153 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4154 nsecs_t splitDownTime) {
4155 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156
4157 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004158 std::vector<PointerProperties> splitPointerProperties;
4159 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004161 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 uint32_t splitPointerCount = 0;
4163
4164 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004167 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004169 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004171 splitPointerProperties.push_back(pointerProperties);
4172 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 splitPointerCount += 1;
4174 }
4175 }
4176
4177 if (splitPointerCount != pointerIds.count()) {
4178 // This is bad. We are missing some of the pointers that we expected to deliver.
4179 // Most likely this indicates that we received an ACTION_MOVE events that has
4180 // different pointer ids than we expected based on the previous ACTION_DOWN
4181 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4182 // in this way.
4183 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004184 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004185 "a broken sequence of pointer ids from the input device: %s",
4186 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004187 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 }
4189
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004190 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4193 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004194 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004196 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004198 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 if (pointerIds.count() == 1) {
4200 // The first/last pointer went down/up.
4201 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004203 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4204 ? AMOTION_EVENT_ACTION_CANCEL
4205 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 } else {
4207 // A secondary pointer went down/up.
4208 uint32_t splitPointerIndex = 0;
4209 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4210 splitPointerIndex += 1;
4211 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 action = maskedAction |
4213 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 }
4215 } else {
4216 // An unrelated pointer changed.
4217 action = AMOTION_EVENT_ACTION_MOVE;
4218 }
4219 }
4220
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004221 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4222 logDispatchStateLocked();
4223 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4224 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4225 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004226 }
4227
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004228 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004229 ATRACE_NAME_IF(ATRACE_ENABLED(),
4230 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4231 ").",
4232 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 std::unique_ptr<MotionEntry> splitMotionEntry =
4234 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4235 originalMotionEntry.deviceId, originalMotionEntry.source,
4236 originalMotionEntry.displayId,
4237 originalMotionEntry.policyFlags, action,
4238 originalMotionEntry.actionButton,
4239 originalMotionEntry.flags, originalMotionEntry.metaState,
4240 originalMotionEntry.buttonState,
4241 originalMotionEntry.classification,
4242 originalMotionEntry.edgeFlags,
4243 originalMotionEntry.xPrecision,
4244 originalMotionEntry.yPrecision,
4245 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004246 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004247 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004249 if (originalMotionEntry.injectionState) {
4250 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 splitMotionEntry->injectionState->refCount += 1;
4252 }
4253
4254 return splitMotionEntry;
4255}
4256
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004257void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4258 std::scoped_lock _l(mLock);
4259 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4260}
4261
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004262void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004263 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004264 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
Antonio Kantekf16f2832021-09-28 04:39:20 +00004267 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004269 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004272 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004273 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 } // release lock
4275
4276 if (needWake) {
4277 mLooper->wake();
4278 }
4279}
4280
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004281void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004282 ALOGD_IF(debugInboundEventDetails(),
4283 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4284 ", deviceId=%d, source=%s, displayId=%" PRId32
4285 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4286 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004287 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4288 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4289 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004290 Result<void> keyCheck = validateKeyEvent(args.action);
4291 if (!keyCheck.ok()) {
4292 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 return;
4294 }
4295
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004296 uint32_t policyFlags = args.policyFlags;
4297 int32_t flags = args.flags;
4298 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004299 // InputDispatcher tracks and generates key repeats on behalf of
4300 // whatever notifies it, so repeatCount should always be set to 0
4301 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4303 policyFlags |= POLICY_FLAG_VIRTUAL;
4304 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 if (policyFlags & POLICY_FLAG_FUNCTION) {
4307 metaState |= AMETA_FUNCTION_ON;
4308 }
4309
4310 policyFlags |= POLICY_FLAG_TRUSTED;
4311
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004312 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004314 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4315 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4316 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
Michael Wright2b3c3302018-03-02 17:19:13 +00004318 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004319 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004320 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4321 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004322 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324
Antonio Kantekf16f2832021-09-28 04:39:20 +00004325 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 { // acquire lock
4327 mLock.lock();
4328
4329 if (shouldSendKeyToInputFilterLocked(args)) {
4330 mLock.unlock();
4331
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004332 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004333 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 return; // event was consumed by the filter
4335 }
4336
4337 mLock.lock();
4338 }
4339
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004340 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004341 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4342 args.displayId, policyFlags, args.action, flags, keyCode,
4343 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004345 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 mLock.unlock();
4347 } // release lock
4348
4349 if (needWake) {
4350 mLooper->wake();
4351 }
4352}
4353
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004354bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 return mInputFilterEnabled;
4356}
4357
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004358void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004359 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004360 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004361 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004362 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004363 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4364 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004365 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4366 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4367 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4368 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4369 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004370 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004371 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4372 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 i, args.pointerProperties[i].id,
4374 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4375 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4376 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4377 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4378 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4379 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4380 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4381 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4382 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4383 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004386
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004387 Result<void> motionCheck =
4388 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4389 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004390 if (!motionCheck.ok()) {
4391 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4392 return;
4393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004395 if (DEBUG_VERIFY_EVENTS) {
4396 auto [it, _] =
4397 mVerifiersByDisplay.try_emplace(args.displayId,
4398 StringPrintf("display %" PRId32, args.displayId));
4399 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004400 it->second.processMovement(args.deviceId, args.source, args.action,
4401 args.getPointerCount(), args.pointerProperties.data(),
4402 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004403 if (!result.ok()) {
4404 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4405 }
4406 }
4407
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004408 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004410
4411 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004412 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004413 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4414 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417
Antonio Kantekf16f2832021-09-28 04:39:20 +00004418 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 { // acquire lock
4420 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004421 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4422 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4423 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004424 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004425 if (touchStateIt != mTouchStatesByDisplay.end()) {
4426 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004427 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004428 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4429 }
4430 }
4431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432
4433 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004434 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004436 displayTransform = it->second.transform;
4437 }
4438
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 mLock.unlock();
4440
4441 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004442 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4443 args.action, args.actionButton, args.flags, args.edgeFlags,
4444 args.metaState, args.buttonState, args.classification,
4445 displayTransform, args.xPrecision, args.yPrecision,
4446 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004447 args.downTime, args.eventTime, args.getPointerCount(),
4448 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449
4450 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004451 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 return; // event was consumed by the filter
4453 }
4454
4455 mLock.lock();
4456 }
4457
4458 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004459 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004460 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4461 args.displayId, policyFlags, args.action,
4462 args.actionButton, args.flags, args.metaState,
4463 args.buttonState, args.classification, args.edgeFlags,
4464 args.xPrecision, args.yPrecision,
4465 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004466 args.downTime, args.pointerProperties,
4467 args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004469 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4470 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004471 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004472 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004473 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4474 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4475 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004476 }
4477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004478 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 mLock.unlock();
4480 } // release lock
4481
4482 if (needWake) {
4483 mLooper->wake();
4484 }
4485}
4486
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004488 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004489 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4490 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004491 args.id, args.eventTime, args.deviceId, args.source,
4492 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004493 }
Chris Yef59a2f42020-10-16 12:55:26 -07004494
Antonio Kantekf16f2832021-09-28 04:39:20 +00004495 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004496 { // acquire lock
4497 mLock.lock();
4498
4499 // Just enqueue a new sensor event.
4500 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004501 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4502 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4503 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004504
4505 needWake = enqueueInboundEventLocked(std::move(newEntry));
4506 mLock.unlock();
4507 } // release lock
4508
4509 if (needWake) {
4510 mLooper->wake();
4511 }
4512}
4513
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004514void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004515 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004516 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4517 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004518 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004519 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004520}
4521
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004522bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004523 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524}
4525
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004526void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004527 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004528 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4529 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004530 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004533 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004535 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536}
4537
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004538void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004539 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004540 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4541 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543
Antonio Kantekf16f2832021-09-28 04:39:20 +00004544 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004546 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004548 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004549 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004550 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004551
4552 for (auto& [_, verifier] : mVerifiersByDisplay) {
4553 verifier.resetDevice(args.deviceId);
4554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 } // release lock
4556
4557 if (needWake) {
4558 mLooper->wake();
4559 }
4560}
4561
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004562void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004563 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004564 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4565 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004566 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004567
Antonio Kantekf16f2832021-09-28 04:39:20 +00004568 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004569 { // acquire lock
4570 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004571 auto entry =
4572 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004573 needWake = enqueueInboundEventLocked(std::move(entry));
4574 } // release lock
4575
4576 if (needWake) {
4577 mLooper->wake();
4578 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004579}
4580
Prabir Pradhan5735a322022-04-11 17:23:34 +00004581InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004582 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004583 InputEventInjectionSync syncMode,
4584 std::chrono::milliseconds timeout,
4585 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004586 Result<void> eventValidation = validateInputEvent(*event);
4587 if (!eventValidation.ok()) {
4588 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4589 return InputEventInjectionResult::FAILED;
4590 }
4591
Prabir Pradhan65613802023-02-22 23:36:58 +00004592 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004593 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4594 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4595 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4596 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004597 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004598 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599
Prabir Pradhan5735a322022-04-11 17:23:34 +00004600 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004602 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004603 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4604 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4605 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4606 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4607 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004608 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004609 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004610 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004611 }
4612
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004613 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004615 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004616 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004617 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004618 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004619 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4620 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4621 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004622 int32_t keyCode = incomingKey.getKeyCode();
4623 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004624 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004625 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004626 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4627 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4628 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004630 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4631 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004632 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633
4634 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4635 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004636 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004637 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4638 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4639 std::to_string(t.duration().count()).c_str());
4640 }
4641 }
4642
4643 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004644 std::unique_ptr<KeyEntry> injectedEntry =
4645 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004646 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004647 incomingKey.getDisplayId(), policyFlags, action,
4648 flags, keyCode, incomingKey.getScanCode(), metaState,
4649 incomingKey.getRepeatCount(),
4650 incomingKey.getDownTime());
4651 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 }
4654
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004655 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004656 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004657 const bool isPointerEvent =
4658 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4659 // If a pointer event has no displayId specified, inject it to the default display.
4660 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4661 ? ADISPLAY_ID_DEFAULT
4662 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004663 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004664
4665 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004666 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004667 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004668 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004669 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4670 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4671 std::to_string(t.duration().count()).c_str());
4672 }
4673 }
4674
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004675 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4676 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4677 }
4678
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004680 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004681 const size_t pointerCount = motionEvent.getPointerCount();
4682 const std::vector<PointerProperties>
4683 pointerProperties(motionEvent.getPointerProperties(),
4684 motionEvent.getPointerProperties() + pointerCount);
4685
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004686 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004687 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004688 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4689 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004690 displayId, policyFlags, motionEvent.getAction(),
4691 motionEvent.getActionButton(), flags,
4692 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004693 motionEvent.getButtonState(),
4694 motionEvent.getClassification(),
4695 motionEvent.getEdgeFlags(),
4696 motionEvent.getXPrecision(),
4697 motionEvent.getYPrecision(),
4698 motionEvent.getRawXCursorPosition(),
4699 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004700 motionEvent.getDownTime(), pointerProperties,
4701 std::vector<PointerCoords>(samplePointerCoords,
4702 samplePointerCoords +
4703 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004704 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004705 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004706 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004707 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004708 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004709 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
4710 MotionEntry>(motionEvent.getId(), *sampleEventTimes, resolvedDeviceId,
4711 motionEvent.getSource(), displayId, policyFlags,
4712 motionEvent.getAction(), motionEvent.getActionButton(), flags,
4713 motionEvent.getMetaState(), motionEvent.getButtonState(),
4714 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4715 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4716 motionEvent.getRawXCursorPosition(),
4717 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4718 pointerProperties,
4719 std::vector<PointerCoords>(samplePointerCoords,
4720 samplePointerCoords +
4721 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004722 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4723 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004724 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 }
4726 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004729 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004730 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004731 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 }
4733
Prabir Pradhan5735a322022-04-11 17:23:34 +00004734 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004735 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 injectionState->injectionIsAsync = true;
4737 }
4738
4739 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004740 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741
4742 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004743 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004744 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004745 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004746 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004747 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004748 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 }
4750
4751 mLock.unlock();
4752
4753 if (needWake) {
4754 mLooper->wake();
4755 }
4756
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004757 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004759 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004761 if (syncMode == InputEventInjectionSync::NONE) {
4762 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 } else {
4764 for (;;) {
4765 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004766 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 break;
4768 }
4769
4770 nsecs_t remainingTimeout = endTime - now();
4771 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004772 if (DEBUG_INJECTION) {
4773 ALOGD("injectInputEvent - Timed out waiting for injection result "
4774 "to become available.");
4775 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004776 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 break;
4778 }
4779
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004780 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 }
4782
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004783 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4784 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004786 if (DEBUG_INJECTION) {
4787 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4788 injectionState->pendingForegroundDispatches);
4789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 nsecs_t remainingTimeout = endTime - now();
4791 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004792 if (DEBUG_INJECTION) {
4793 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4794 "dispatches to finish.");
4795 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 break;
4798 }
4799
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004800 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802 }
4803 }
4804
4805 injectionState->release();
4806 } // release lock
4807
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004808 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004809 LOG(INFO) << "injectInputEvent - Finished with result "
4810 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812
4813 return injectionResult;
4814}
4815
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004816std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004817 std::array<uint8_t, 32> calculatedHmac;
4818 std::unique_ptr<VerifiedInputEvent> result;
4819 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004820 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004821 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4822 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4823 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004824 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004825 break;
4826 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004827 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004828 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4829 VerifiedMotionEvent verifiedMotionEvent =
4830 verifiedMotionEventFromMotionEvent(motionEvent);
4831 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004832 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004833 break;
4834 }
4835 default: {
4836 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4837 return nullptr;
4838 }
4839 }
4840 if (calculatedHmac == INVALID_HMAC) {
4841 return nullptr;
4842 }
tyiu1573a672023-02-21 22:38:32 +00004843 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004844 return nullptr;
4845 }
4846 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004847}
4848
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004849void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004850 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004851 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004853 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004854 LOG(INFO) << "Setting input event injection result to "
4855 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004858 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 // Log the outcome since the injector did not wait for the injection result.
4860 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004861 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862 ALOGV("Asynchronous input event injection succeeded.");
4863 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004864 case InputEventInjectionResult::TARGET_MISMATCH:
4865 ALOGV("Asynchronous input event injection target mismatch.");
4866 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004867 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004868 ALOGW("Asynchronous input event injection failed.");
4869 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004870 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004871 ALOGW("Asynchronous input event injection timed out.");
4872 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004873 case InputEventInjectionResult::PENDING:
4874 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4875 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877 }
4878
4879 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004880 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 }
4882}
4883
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004884void InputDispatcher::transformMotionEntryForInjectionLocked(
4885 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004886 // Input injection works in the logical display coordinate space, but the input pipeline works
4887 // display space, so we need to transform the injected events accordingly.
4888 const auto it = mDisplayInfos.find(entry.displayId);
4889 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004890 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004891
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004892 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4893 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4894 const vec2 cursor =
4895 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4896 {entry.xCursorPosition, entry.yCursorPosition});
4897 entry.xCursorPosition = cursor.x;
4898 entry.yCursorPosition = cursor.y;
4899 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004900 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004901 entry.pointerCoords[i] =
4902 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4903 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004904 }
4905}
4906
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004907void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4908 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 if (injectionState) {
4910 injectionState->pendingForegroundDispatches += 1;
4911 }
4912}
4913
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004914void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4915 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 if (injectionState) {
4917 injectionState->pendingForegroundDispatches -= 1;
4918
4919 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004920 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 }
4922 }
4923}
4924
chaviw98318de2021-05-19 16:45:23 -05004925const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004926 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004927 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004928 auto it = mWindowHandlesByDisplay.find(displayId);
4929 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004930}
4931
chaviw98318de2021-05-19 16:45:23 -05004932sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004933 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004934 if (windowHandleToken == nullptr) {
4935 return nullptr;
4936 }
4937
Prabir Pradhan16463382023-10-12 23:03:19 +00004938 if (!displayId) {
4939 // Look through all displays.
4940 for (auto& it : mWindowHandlesByDisplay) {
4941 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4942 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4943 if (windowHandle->getToken() == windowHandleToken) {
4944 return windowHandle;
4945 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004948 return nullptr;
4949 }
4950
Prabir Pradhan16463382023-10-12 23:03:19 +00004951 // Only look through the requested display.
4952 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004953 if (windowHandle->getToken() == windowHandleToken) {
4954 return windowHandle;
4955 }
4956 }
4957 return nullptr;
4958}
4959
chaviw98318de2021-05-19 16:45:23 -05004960sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4961 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004962 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004963 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4964 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004965 if (handle->getId() == windowHandle->getId() &&
4966 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004967 if (windowHandle->getInfo()->displayId != it.first) {
4968 ALOGE("Found window %s in display %" PRId32
4969 ", but it should belong to display %" PRId32,
4970 windowHandle->getName().c_str(), it.first,
4971 windowHandle->getInfo()->displayId);
4972 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004973 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 }
4976 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004977 return nullptr;
4978}
4979
chaviw98318de2021-05-19 16:45:23 -05004980sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004981 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4982 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983}
4984
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004985ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4986 auto displayInfoIt = mDisplayInfos.find(displayId);
4987 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4988 : kIdentityTransform;
4989}
4990
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004991bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4992 const MotionEntry& motionEntry) const {
4993 const WindowInfo& info = *window->getInfo();
4994
4995 // Skip spy window targets that are not valid for targeted injection.
4996 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004997 return false;
4998 }
4999
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005000 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5001 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5002 return false;
5003 }
5004
5005 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5006 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5007 window->getName().c_str());
5008 return false;
5009 }
5010
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005011 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005012 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005013 ALOGW("Not sending touch to %s because there's no corresponding connection",
5014 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005015 return false;
5016 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005017
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005018 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005019 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005020 return false;
5021 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005022
5023 // Drop events that can't be trusted due to occlusion
5024 const auto [x, y] = resolveTouchedPosition(motionEntry);
5025 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5026 if (!isTouchTrustedLocked(occlusionInfo)) {
5027 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005028 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005029 for (const auto& log : occlusionInfo.debugInfo) {
5030 ALOGD("%s", log.c_str());
5031 }
5032 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005033 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5034 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005035 return false;
5036 }
5037
5038 // Drop touch events if requested by input feature
5039 if (shouldDropInput(motionEntry, window)) {
5040 return false;
5041 }
5042
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005043 return true;
5044}
5045
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005046std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5047 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005048 auto connectionIt = mConnectionsByToken.find(token);
5049 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005050 return nullptr;
5051 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005052 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005053}
5054
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005055void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005056 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5057 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005058 // Remove all handles on a display if there are no windows left.
5059 mWindowHandlesByDisplay.erase(displayId);
5060 return;
5061 }
5062
5063 // Since we compare the pointer of input window handles across window updates, we need
5064 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005065 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5066 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5067 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005068 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005069 }
5070
chaviw98318de2021-05-19 16:45:23 -05005071 std::vector<sp<WindowInfoHandle>> newHandles;
5072 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005073 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005074 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005075 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005076 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005077 const bool canReceiveInput =
5078 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5079 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005080 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005081 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005082 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005083 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005084 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005085 }
5086
5087 if (info->displayId != displayId) {
5088 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5089 handle->getName().c_str(), displayId, info->displayId);
5090 continue;
5091 }
5092
Robert Carredd13602020-04-13 17:24:34 -07005093 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5094 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005095 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005096 oldHandle->updateFrom(handle);
5097 newHandles.push_back(oldHandle);
5098 } else {
5099 newHandles.push_back(handle);
5100 }
5101 }
5102
5103 // Insert or replace
5104 mWindowHandlesByDisplay[displayId] = newHandles;
5105}
5106
Arthur Hungb92218b2018-08-14 12:00:21 +08005107/**
5108 * Called from InputManagerService, update window handle list by displayId that can receive input.
5109 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5110 * If set an empty list, remove all handles from the specific display.
5111 * For focused handle, check if need to change and send a cancel event to previous one.
5112 * For removed handle, check if need to send a cancel event if already in touch.
5113 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005114void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005115 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005116 if (DEBUG_FOCUS) {
5117 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005118 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005119 windowList += iwh->getName() + " ";
5120 }
5121 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123
Prabir Pradhand65552b2021-10-07 11:23:50 -07005124 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005125 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005126 const WindowInfo& info = *window->getInfo();
5127
5128 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005129 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005130 if (noInputWindow && window->getToken() != nullptr) {
5131 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5132 window->getName().c_str());
5133 window->releaseChannel();
5134 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005135
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005136 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005137 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5138 !info.inputConfig.test(
5139 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005140 "%s has feature SPY, but is not a trusted overlay.",
5141 window->getName().c_str());
5142
Prabir Pradhand65552b2021-10-07 11:23:50 -07005143 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005144 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5145 !info.inputConfig.test(
5146 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005147 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5148 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005149 }
5150
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005152 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153
chaviw98318de2021-05-19 16:45:23 -05005154 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005155
chaviw98318de2021-05-19 16:45:23 -05005156 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005157
Vishnu Nairc519ff72021-01-21 08:23:08 -08005158 std::optional<FocusResolver::FocusChanges> changes =
5159 mFocusResolver.setInputWindows(displayId, windowHandles);
5160 if (changes) {
5161 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005164 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5165 mTouchStatesByDisplay.find(displayId);
5166 if (stateIt != mTouchStatesByDisplay.end()) {
5167 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005168 for (size_t i = 0; i < state.windows.size();) {
5169 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005170 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005171 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5172 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005173 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005174 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5175 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005176 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005177 "touched window was removed");
5178 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005179 // Since we are about to drop the touch, cancel the events for the wallpaper as
5180 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005181 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005182 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5183 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005184 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005185 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005188 state.windows.erase(state.windows.begin() + i);
5189 } else {
5190 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 }
5192 }
arthurhungb89ccb02020-12-30 16:19:01 +08005193
arthurhung6d4bed92021-03-17 11:59:33 +08005194 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005195 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005196 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005197 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005198 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005199 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5200 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005201 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005202 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005203 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005204
Arthur Hung72d8dc32020-03-28 00:48:39 +00005205 // Release information for windows that are no longer present.
5206 // This ensures that unused input channels are released promptly.
5207 // Otherwise, they might stick around until the window handle is destroyed
5208 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005209 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005210 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005211 if (DEBUG_FOCUS) {
5212 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005213 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005214 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005215 }
chaviw291d88a2019-02-14 10:33:58 -08005216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217}
5218
5219void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005220 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005221 if (DEBUG_FOCUS) {
5222 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5223 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5224 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005225 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005226 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005227 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228 } // release lock
5229
5230 // Wake up poll loop since it may need to make new input dispatching choices.
5231 mLooper->wake();
5232}
5233
Vishnu Nair599f1412021-06-21 10:39:58 -07005234void InputDispatcher::setFocusedApplicationLocked(
5235 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5236 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5237 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5238
5239 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5240 return; // This application is already focused. No need to wake up or change anything.
5241 }
5242
5243 // Set the new application handle.
5244 if (inputApplicationHandle != nullptr) {
5245 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5246 } else {
5247 mFocusedApplicationHandlesByDisplay.erase(displayId);
5248 }
5249
5250 // No matter what the old focused application was, stop waiting on it because it is
5251 // no longer focused.
5252 resetNoFocusedWindowTimeoutLocked();
5253}
5254
Tiger Huang721e26f2018-07-24 22:26:19 +08005255/**
5256 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5257 * the display not specified.
5258 *
5259 * We track any unreleased events for each window. If a window loses the ability to receive the
5260 * released event, we will send a cancel event to it. So when the focused display is changed, we
5261 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5262 * display. The display-specified events won't be affected.
5263 */
5264void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005265 if (DEBUG_FOCUS) {
5266 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5267 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005268 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005269 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005270
5271 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005272 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005273 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005274 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005275 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005276 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005277 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005278 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005279 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005281 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005282 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5283 }
5284 }
5285 mFocusedDisplayId = displayId;
5286
Chris Ye3c2d6f52020-08-09 10:39:48 -07005287 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005288 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005289 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005290
Vishnu Nairad321cd2020-08-20 16:40:21 -07005291 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005292 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005293 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005294 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005295 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005296 }
5297 }
5298 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005299 } // release lock
5300
5301 // Wake up poll loop since it may need to make new input dispatching choices.
5302 mLooper->wake();
5303}
5304
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005306 if (DEBUG_FOCUS) {
5307 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309
5310 bool changed;
5311 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005312 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5315 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005316 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 }
5318
5319 if (mDispatchEnabled && !enabled) {
5320 resetAndDropEverythingLocked("dispatcher is being disabled");
5321 }
5322
5323 mDispatchEnabled = enabled;
5324 mDispatchFrozen = frozen;
5325 changed = true;
5326 } else {
5327 changed = false;
5328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 } // release lock
5330
5331 if (changed) {
5332 // Wake up poll loop since it may need to make new input dispatching choices.
5333 mLooper->wake();
5334 }
5335}
5336
5337void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005338 if (DEBUG_FOCUS) {
5339 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341
5342 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005343 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344
5345 if (mInputFilterEnabled == enabled) {
5346 return;
5347 }
5348
5349 mInputFilterEnabled = enabled;
5350 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5351 } // release lock
5352
5353 // Wake up poll loop since there might be work to do to drop everything.
5354 mLooper->wake();
5355}
5356
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005357bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005358 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005359 bool needWake = false;
5360 {
5361 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005362 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005363 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005364 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005365 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5366 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005367 mTouchModePerDisplay.count(displayId) == 0
5368 ? "not set"
5369 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5370
Antonio Kantek15beb512022-06-13 22:35:41 +00005371 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5372 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005373 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005374 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005375 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005376 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5377 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005378 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005379 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005380 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005381 return false;
5382 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005383 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005384 mTouchModePerDisplay[displayId] = inTouchMode;
5385 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5386 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005387 needWake = enqueueInboundEventLocked(std::move(entry));
5388 } // release lock
5389
5390 if (needWake) {
5391 mLooper->wake();
5392 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005393 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005394}
5395
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005396bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005397 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5398 if (focusedToken == nullptr) {
5399 return false;
5400 }
5401 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5402 return isWindowOwnedBy(windowHandle, pid, uid);
5403}
5404
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005405bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005406 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5407 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5408 const sp<WindowInfoHandle> windowHandle =
5409 getWindowHandleLocked(connectionToken);
5410 return isWindowOwnedBy(windowHandle, pid, uid);
5411 }) != mInteractionConnectionTokens.end();
5412}
5413
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005414void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5415 if (opacity < 0 || opacity > 1) {
5416 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5417 return;
5418 }
5419
5420 std::scoped_lock lock(mLock);
5421 mMaximumObscuringOpacityForTouch = opacity;
5422}
5423
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005424std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5425InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005426 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5427 for (TouchedWindow& w : state.windows) {
5428 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005429 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005430 }
5431 }
5432 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005433 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434}
5435
arthurhungb89ccb02020-12-30 16:19:01 +08005436bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5437 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005438 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005439 if (DEBUG_FOCUS) {
5440 ALOGD("Trivial transfer to same window.");
5441 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005442 return true;
5443 }
5444
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005446 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447
Arthur Hungabbb9d82021-09-01 14:52:30 +00005448 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005449 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005450
Arthur Hungabbb9d82021-09-01 14:52:30 +00005451 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005452 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 return false;
5454 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005455 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5456 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005457 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5458 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005459 return false;
5460 }
5461 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005462
Arthur Hungabbb9d82021-09-01 14:52:30 +00005463 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5464 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005465 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005466 return false;
5467 }
5468
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005469 if (DEBUG_FOCUS) {
5470 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005471 touchedWindow->windowHandle->getName().c_str(),
5472 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 }
5474
Arthur Hungabbb9d82021-09-01 14:52:30 +00005475 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005476 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005477 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005478 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005479 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480
Arthur Hungabbb9d82021-09-01 14:52:30 +00005481 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005482 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005483 ftl::Flags<InputTarget::Flags> newTargetFlags =
5484 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005485 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005486 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005487 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005488 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5489 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490
Arthur Hungabbb9d82021-09-01 14:52:30 +00005491 // Store the dragging window.
5492 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005493 if (pointerIds.count() != 1) {
5494 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5495 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005496 return false;
5497 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005498 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005499 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005500 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 }
5502
Arthur Hungabbb9d82021-09-01 14:52:30 +00005503 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005504 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5505 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005506 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005507 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005508 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5509 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005511 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5512 newTargetFlags);
5513
5514 // Check if the wallpaper window should deliver the corresponding event.
5515 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005516 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 } // release lock
5519
5520 // Wake up poll loop since it may need to make new input dispatching choices.
5521 mLooper->wake();
5522 return true;
5523}
5524
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005525/**
5526 * Get the touched foreground window on the given display.
5527 * Return null if there are no windows touched on that display, or if more than one foreground
5528 * window is being touched.
5529 */
5530sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5531 auto stateIt = mTouchStatesByDisplay.find(displayId);
5532 if (stateIt == mTouchStatesByDisplay.end()) {
5533 ALOGI("No touch state on display %" PRId32, displayId);
5534 return nullptr;
5535 }
5536
5537 const TouchState& state = stateIt->second;
5538 sp<WindowInfoHandle> touchedForegroundWindow;
5539 // If multiple foreground windows are touched, return nullptr
5540 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005541 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005542 if (touchedForegroundWindow != nullptr) {
5543 ALOGI("Two or more foreground windows: %s and %s",
5544 touchedForegroundWindow->getName().c_str(),
5545 window.windowHandle->getName().c_str());
5546 return nullptr;
5547 }
5548 touchedForegroundWindow = window.windowHandle;
5549 }
5550 }
5551 return touchedForegroundWindow;
5552}
5553
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005554// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005555bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005556 sp<IBinder> fromToken;
5557 { // acquire lock
5558 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005559 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005560 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005561 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5562 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005563 return false;
5564 }
5565
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005566 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5567 if (from == nullptr) {
5568 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5569 return false;
5570 }
5571
5572 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005573 } // release lock
5574
5575 return transferTouchFocus(fromToken, destChannelToken);
5576}
5577
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005579 if (DEBUG_FOCUS) {
5580 ALOGD("Resetting and dropping all events (%s).", reason);
5581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582
Michael Wrightfb04fd52022-11-24 22:31:11 +00005583 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 synthesizeCancelationEventsForAllConnectionsLocked(options);
5585
5586 resetKeyRepeatLocked();
5587 releasePendingEventLocked();
5588 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005589 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005591 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005592 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593}
5594
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005595void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005596 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 dumpDispatchStateLocked(dump);
5598
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005599 std::istringstream stream(dump);
5600 std::string line;
5601
5602 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005603 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 }
5605}
5606
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005607std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005608 std::string dump;
5609
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005610 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5611 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005612
5613 std::string windowName = "None";
5614 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005615 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005616 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5617 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5618 : "token has capture without window";
5619 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005620 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005621
5622 return dump;
5623}
5624
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005625void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005626 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5627 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5628 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005629 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630
Tiger Huang721e26f2018-07-24 22:26:19 +08005631 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5632 dump += StringPrintf(INDENT "FocusedApplications:\n");
5633 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5634 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005635 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005636 const std::chrono::duration timeout =
5637 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005638 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005639 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005640 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005643 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005645
Vishnu Nairc519ff72021-01-21 08:23:08 -08005646 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005647 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005649 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005650 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005651 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005652 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5653 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 }
5655 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005656 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 }
5658
arthurhung6d4bed92021-03-17 11:59:33 +08005659 if (mDragState) {
5660 dump += StringPrintf(INDENT "DragState:\n");
5661 mDragState->dump(dump, INDENT2);
5662 }
5663
Arthur Hungb92218b2018-08-14 12:00:21 +08005664 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005665 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5666 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5667 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5668 const auto& displayInfo = it->second;
5669 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5670 displayInfo.logicalHeight);
5671 displayInfo.transform.dump(dump, "transform", INDENT4);
5672 } else {
5673 dump += INDENT2 "No DisplayInfo found!\n";
5674 }
5675
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005676 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005677 dump += INDENT2 "Windows:\n";
5678 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005679 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5680 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005682 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005683 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005684 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005685 "applicationInfo.name=%s, "
5686 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005687 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005688 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005689 windowInfo->displayId,
5690 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005691 windowInfo->alpha, windowInfo->frame.left,
5692 windowInfo->frame.top, windowInfo->frame.right,
5693 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005694 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005695 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005696 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005697 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005698 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005699 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005700 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005701 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005702 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005703 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005704 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005705 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005706 }
5707 } else {
5708 dump += INDENT2 "Windows: <none>\n";
5709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 }
5711 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005712 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 }
5714
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005715 if (!mGlobalMonitorsByDisplay.empty()) {
5716 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5717 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005718 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005721 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 }
5723
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005724 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725
5726 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005727 if (!mRecentQueue.empty()) {
5728 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005729 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005730 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005731 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005732 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 }
5734 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005735 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 }
5737
5738 // Dump event currently being dispatched.
5739 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "PendingEvent:\n";
5741 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005742 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005743 dump += StringPrintf(", age=%" PRId64 "ms\n",
5744 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005746 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747 }
5748
5749 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005750 if (!mInboundQueue.empty()) {
5751 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005752 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005753 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005754 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005755 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 }
5757 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005758 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 }
5760
Prabir Pradhancef936d2021-07-21 16:17:52 +00005761 if (!mCommandQueue.empty()) {
5762 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5763 } else {
5764 dump += INDENT "CommandQueue: <empty>\n";
5765 }
5766
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005767 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005768 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005769 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005770 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005771 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005772 connection->inputChannel->getFd().get(),
5773 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005774 connection->getWindowName().c_str(),
5775 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005776 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005778 if (!connection->outboundQueue.empty()) {
5779 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5780 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005781 dump += dumpQueue(connection->outboundQueue, currentTime);
5782
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005784 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005787 if (!connection->waitQueue.empty()) {
5788 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5789 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005790 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005792 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005794 std::stringstream inputStateDump;
5795 inputStateDump << connection->inputState;
5796 if (!isEmpty(inputStateDump)) {
5797 dump += INDENT3 "InputState: ";
5798 dump += inputStateDump.str() + "\n";
5799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 }
5801 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005802 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 }
5804
5805 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005806 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5807 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005809 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 }
5811
Antonio Kantek15beb512022-06-13 22:35:41 +00005812 if (!mTouchModePerDisplay.empty()) {
5813 dump += INDENT "TouchModePerDisplay:\n";
5814 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5815 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5816 std::to_string(touchMode).c_str());
5817 }
5818 } else {
5819 dump += INDENT "TouchModePerDisplay: <none>\n";
5820 }
5821
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005822 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005823 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5824 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5825 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005826 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005827 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828}
5829
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005830void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005831 const size_t numMonitors = monitors.size();
5832 for (size_t i = 0; i < numMonitors; i++) {
5833 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005834 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005835 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5836 dump += "\n";
5837 }
5838}
5839
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005840class LooperEventCallback : public LooperCallback {
5841public:
5842 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5843 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5844
5845private:
5846 std::function<int(int events)> mCallback;
5847};
5848
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005849Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005850 if (DEBUG_CHANNEL_CREATION) {
5851 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005854 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005855 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005856 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005857
5858 if (result) {
5859 return base::Error(result) << "Failed to open input channel pair with name " << name;
5860 }
5861
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005863 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005864 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005865 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005866 std::shared_ptr<Connection> connection =
5867 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5868 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005870 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5871 ALOGE("Created a new connection, but the token %p is already known", token.get());
5872 }
5873 mConnectionsByToken.emplace(token, connection);
5874
5875 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5876 this, std::placeholders::_1, token);
5877
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005878 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5879 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880 } // release lock
5881
5882 // Wake the looper because some connections have changed.
5883 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005884 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885}
5886
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005887Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005888 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005889 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005890 std::shared_ptr<InputChannel> serverChannel;
5891 std::unique_ptr<InputChannel> clientChannel;
5892 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5893 if (result) {
5894 return base::Error(result) << "Failed to open input channel pair with name " << name;
5895 }
5896
Michael Wright3dd60e22019-03-27 22:06:44 +00005897 { // acquire lock
5898 std::scoped_lock _l(mLock);
5899
5900 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005901 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5902 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005903 }
5904
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005905 std::shared_ptr<Connection> connection =
5906 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005907 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005908 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005909
5910 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5911 ALOGE("Created a new connection, but the token %p is already known", token.get());
5912 }
5913 mConnectionsByToken.emplace(token, connection);
5914 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5915 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005916
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005917 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005918
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005919 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5920 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005921 }
Garfield Tan15601662020-09-22 15:32:38 -07005922
Michael Wright3dd60e22019-03-27 22:06:44 +00005923 // Wake the looper because some connections have changed.
5924 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005925 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005926}
5927
Garfield Tan15601662020-09-22 15:32:38 -07005928status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005930 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931
Harry Cutts33476232023-01-30 19:57:29 +00005932 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 if (status) {
5934 return status;
5935 }
5936 } // release lock
5937
5938 // Wake the poll loop because removing the connection may have changed the current
5939 // synchronization state.
5940 mLooper->wake();
5941 return OK;
5942}
5943
Garfield Tan15601662020-09-22 15:32:38 -07005944status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5945 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005946 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005947 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005948 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 return BAD_VALUE;
5950 }
5951
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005952 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005953
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005955 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 }
5957
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005958 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
5960 nsecs_t currentTime = now();
5961 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5962
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005963 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 return OK;
5965}
5966
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005967void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005968 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5969 auto& [displayId, monitors] = *it;
5970 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5971 return monitor.inputChannel->getConnectionToken() == connectionToken;
5972 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005973
Michael Wright3dd60e22019-03-27 22:06:44 +00005974 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005975 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005976 } else {
5977 ++it;
5978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 }
5980}
5981
Michael Wright3dd60e22019-03-27 22:06:44 +00005982status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005983 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005984 return pilferPointersLocked(token);
5985}
Michael Wright3dd60e22019-03-27 22:06:44 +00005986
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005987status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005988 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5989 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005990 LOG(WARNING)
5991 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005992 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005993 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005994
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005995 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005996 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005997 LOG(WARNING)
5998 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5999 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006000 return BAD_VALUE;
6001 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006002 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006003 if (deviceIds.empty()) {
6004 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006005 return BAD_VALUE;
6006 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006007
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006008 for (const DeviceId deviceId : deviceIds) {
6009 TouchState& state = *statePtr;
6010 TouchedWindow& window = *windowPtr;
6011 // Send cancel events to all the input channels we're stealing from.
6012 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6013 "input channel stole pointer stream");
6014 options.deviceId = deviceId;
6015 options.displayId = displayId;
6016 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6017 options.pointerIds = pointerIds;
6018 std::string canceledWindows;
6019 for (const TouchedWindow& w : state.windows) {
6020 const std::shared_ptr<InputChannel> channel =
6021 getInputChannelLocked(w.windowHandle->getToken());
6022 if (channel != nullptr && channel->getConnectionToken() != token) {
6023 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6024 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6025 canceledWindows += channel->getName();
6026 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006027 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006028 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6029 LOG(INFO) << "Channel " << requestingChannel->getName()
6030 << " is stealing input gesture for device " << deviceId << " from "
6031 << canceledWindows;
6032
6033 // Prevent the gesture from being sent to any other windows.
6034 // This only blocks relevant pointers to be sent to other windows
6035 window.addPilferingPointers(deviceId, pointerIds);
6036
6037 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006038 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006039 return OK;
6040}
6041
Prabir Pradhan99987712020-11-10 18:43:05 -08006042void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6043 { // acquire lock
6044 std::scoped_lock _l(mLock);
6045 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006046 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006047 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6048 windowHandle != nullptr ? windowHandle->getName().c_str()
6049 : "token without window");
6050 }
6051
Vishnu Nairc519ff72021-01-21 08:23:08 -08006052 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006053 if (focusedToken != windowToken) {
6054 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6055 enabled ? "enable" : "disable");
6056 return;
6057 }
6058
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006059 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006060 ALOGW("Ignoring request to %s Pointer Capture: "
6061 "window has %s requested pointer capture.",
6062 enabled ? "enable" : "disable", enabled ? "already" : "not");
6063 return;
6064 }
6065
Christine Franksb768bb42021-11-29 12:11:31 -08006066 if (enabled) {
6067 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6068 mIneligibleDisplaysForPointerCapture.end(),
6069 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6070 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6071 return;
6072 }
6073 }
6074
Prabir Pradhan99987712020-11-10 18:43:05 -08006075 setPointerCaptureLocked(enabled);
6076 } // release lock
6077
6078 // Wake the thread to process command entries.
6079 mLooper->wake();
6080}
6081
Christine Franksb768bb42021-11-29 12:11:31 -08006082void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6083 { // acquire lock
6084 std::scoped_lock _l(mLock);
6085 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6086 if (!isEligible) {
6087 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6088 }
6089 } // release lock
6090}
6091
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006092std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006093 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006094 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006095 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006096 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006097 }
6098 }
6099 }
6100 return std::nullopt;
6101}
6102
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006103std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6104 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006105 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006106 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006107 }
6108
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006109 for (const auto& [token, connection] : mConnectionsByToken) {
6110 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006111 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112 }
6113 }
Robert Carr4e670e52018-08-15 13:26:12 -07006114
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006115 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116}
6117
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006118std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006119 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006120 if (connection == nullptr) {
6121 return "<nullptr>";
6122 }
6123 return connection->getInputChannelName();
6124}
6125
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006126void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006127 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006128 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006129}
6130
Prabir Pradhancef936d2021-07-21 16:17:52 +00006131void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006132 const std::shared_ptr<Connection>& connection,
6133 uint32_t seq, bool handled,
6134 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006135 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006136 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006137
6138 { // Start critical section
6139 auto dispatchEntryIt =
6140 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6141 [seq](auto& e) { return e->seq == seq; });
6142 if (dispatchEntryIt == connection->waitQueue.end()) {
6143 return;
6144 }
6145
6146 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6147
6148 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6149 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6150 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6151 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6152 }
6153 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6154 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6155 connection->inputChannel->getConnectionToken(),
6156 dispatchEntry.deliveryTime, consumeTime, finishTime);
6157 }
6158
6159 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6160 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6161 restartEvent =
6162 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6163 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6164 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6165 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6166 motionEntry, handled);
6167 } else {
6168 restartEvent = false;
6169 }
6170 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171
6172 // Dequeue the event and start the next cycle.
6173 // Because the lock might have been released, it is possible that the
6174 // contents of the wait queue to have been drained, so we need to double-check
6175 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006176 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6177 [seq](auto& e) { return e->seq == seq; });
6178 if (entryIt != connection->waitQueue.end()) {
6179 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6180 connection->waitQueue.erase(entryIt);
6181
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6183 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6184 if (!connection->responsive) {
6185 connection->responsive = isConnectionResponsive(*connection);
6186 if (connection->responsive) {
6187 // The connection was unresponsive, and now it's responsive.
6188 processConnectionResponsiveLocked(*connection);
6189 }
6190 }
6191 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006192 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006193 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006194 traceOutboundQueueLength(*connection);
6195 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006196 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006197 }
6198 }
6199
6200 // Start the next dispatch cycle for this connection.
6201 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006202}
6203
Prabir Pradhancef936d2021-07-21 16:17:52 +00006204void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6205 const sp<IBinder>& newToken) {
6206 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6207 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006208 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006209 };
6210 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211}
6212
Prabir Pradhancef936d2021-07-21 16:17:52 +00006213void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6214 auto command = [this, token, x, y]() REQUIRES(mLock) {
6215 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006216 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006217 };
6218 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006219}
6220
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006221void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006222 if (connection == nullptr) {
6223 LOG_ALWAYS_FATAL("Caller must check for nullness");
6224 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006225 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6226 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006227 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006228 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006229 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006230 return;
6231 }
6232 /**
6233 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6234 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6235 * has changed. This could cause newer entries to time out before the already dispatched
6236 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6237 * processes the events linearly. So providing information about the oldest entry seems to be
6238 * most useful.
6239 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006240 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6241 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006242 std::string reason =
6243 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006244 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006245 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006246 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006247 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006248 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006249
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006250 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6251
6252 // Stop waking up for events on this connection, it is already unresponsive
6253 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006254}
6255
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006256void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6257 std::string reason =
6258 StringPrintf("%s does not have a focused window", application->getName().c_str());
6259 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006260
Yabin Cui8eb9c552023-06-08 18:05:07 +00006261 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006262 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006263 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264 };
6265 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006266}
6267
chaviw98318de2021-05-19 16:45:23 -05006268void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006269 const std::string& reason) {
6270 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6271 updateLastAnrStateLocked(windowLabel, reason);
6272}
6273
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006274void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6275 const std::string& reason) {
6276 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006277 updateLastAnrStateLocked(windowLabel, reason);
6278}
6279
6280void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6281 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006283 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284 struct tm tm;
6285 localtime_r(&t, &tm);
6286 char timestr[64];
6287 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006288 mLastAnrState.clear();
6289 mLastAnrState += INDENT "ANR:\n";
6290 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006291 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6292 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006293 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294}
6295
Prabir Pradhancef936d2021-07-21 16:17:52 +00006296void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6297 KeyEntry& entry) {
6298 const KeyEvent event = createKeyEvent(entry);
6299 nsecs_t delay = 0;
6300 { // release lock
6301 scoped_unlock unlock(mLock);
6302 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006303 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006304 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6305 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6306 std::to_string(t.duration().count()).c_str());
6307 }
6308 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309
6310 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006311 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006312 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006313 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006315 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006316 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318}
6319
Prabir Pradhancef936d2021-07-21 16:17:52 +00006320void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006321 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006322 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006323 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006324 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006325 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006326 };
6327 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328}
6329
Prabir Pradhanedd96402022-02-15 01:46:16 -08006330void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006331 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006332 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006334 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006335 };
6336 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006337}
6338
6339/**
6340 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6341 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6342 * command entry to the command queue.
6343 */
6344void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6345 std::string reason) {
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) {
6349 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6350 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006351 pid = findMonitorPidByTokenLocked(connectionToken);
6352 } else {
6353 // The connection is a window
6354 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6355 reason.c_str());
6356 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6357 if (handle != nullptr) {
6358 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006359 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006360 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006361 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006362}
6363
6364/**
6365 * Tell the policy that a connection has become responsive so that it can stop ANR.
6366 */
6367void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6368 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006369 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006370 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006371 pid = findMonitorPidByTokenLocked(connectionToken);
6372 } else {
6373 // The connection is a window
6374 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6375 if (handle != nullptr) {
6376 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006377 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006378 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006379 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006380}
6381
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006382bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006383 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006384 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006385 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006386 if (!handled) {
6387 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006388 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006389 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006390 return false;
6391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006393 // Get the fallback key state.
6394 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006395 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006396 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006397 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006398 connection->inputState.removeFallbackKey(originalKeyCode);
6399 }
6400
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006401 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006402 // If the application handles the original key for which we previously
6403 // generated a fallback or if the window is not a foreground window,
6404 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006405 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006406 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006407 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6408 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6409 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6410 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6411 keyEntry.policyFlags);
6412 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006413 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415
6416 mLock.unlock();
6417
Prabir Pradhana41d2442023-04-20 21:30:40 +00006418 if (const auto unhandledKeyFallback =
6419 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6420 event, keyEntry.policyFlags);
6421 unhandledKeyFallback) {
6422 event = *unhandledKeyFallback;
6423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424
6425 mLock.lock();
6426
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006427 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006428 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006429 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430 "application handled the original non-fallback key "
6431 "or is no longer a foreground target, "
6432 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006433 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006434 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006436 connection->inputState.removeFallbackKey(originalKeyCode);
6437 }
6438 } else {
6439 // If the application did not handle a non-fallback key, first check
6440 // that we are in a good state to perform unhandled key event processing
6441 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006442 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006443 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006444 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6445 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6446 "since this is not an initial down. "
6447 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6448 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6449 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450 return false;
6451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006452
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006454 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6455 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6456 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6457 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6458 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006459 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006460
6461 mLock.unlock();
6462
Prabir Pradhana41d2442023-04-20 21:30:40 +00006463 bool fallback = false;
6464 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6465 event, keyEntry.policyFlags);
6466 fb) {
6467 fallback = true;
6468 event = *fb;
6469 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006470
6471 mLock.lock();
6472
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006473 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006474 connection->inputState.removeFallbackKey(originalKeyCode);
6475 return false;
6476 }
6477
6478 // Latch the fallback keycode for this key on an initial down.
6479 // The fallback keycode cannot change at any other point in the lifecycle.
6480 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006481 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006482 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006484 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006486 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 }
6488
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006489 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490
6491 // Cancel the fallback key if the policy decides not to send it anymore.
6492 // We will continue to dispatch the key to the policy but we will no
6493 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6495 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006496 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6497 if (fallback) {
6498 ALOGD("Unhandled key event: Policy requested to send key %d"
6499 "as a fallback for %d, but on the DOWN it had requested "
6500 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006501 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006502 } else {
6503 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6504 "but on the DOWN it had requested to send %d. "
6505 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006509
Michael Wrightfb04fd52022-11-24 22:31:11 +00006510 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006511 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006512 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513 synthesizeCancelationEventsForConnectionLocked(connection, options);
6514
6515 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006516 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006517 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006518 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006519 }
6520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006522 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6523 {
6524 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006525 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006526 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006527 for (const auto& [key, value] : fallbackKeys) {
6528 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006529 }
6530 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6531 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006534
6535 if (fallback) {
6536 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006537 keyEntry.eventTime = event.getEventTime();
6538 keyEntry.deviceId = event.getDeviceId();
6539 keyEntry.source = event.getSource();
6540 keyEntry.displayId = event.getDisplayId();
6541 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006542 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006543 keyEntry.scanCode = event.getScanCode();
6544 keyEntry.metaState = event.getMetaState();
6545 keyEntry.repeatCount = event.getRepeatCount();
6546 keyEntry.downTime = event.getDownTime();
6547 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006548
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006549 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6550 ALOGD("Unhandled key event: Dispatching fallback key. "
6551 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006552 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006553 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006554 return true; // restart the event
6555 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006556 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6557 ALOGD("Unhandled key event: No fallback key.");
6558 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006559
6560 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006561 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 }
6563 }
6564 return false;
6565}
6566
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006567bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006568 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006569 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570 return false;
6571}
6572
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573void InputDispatcher::traceInboundQueueLengthLocked() {
6574 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006575 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006576 }
6577}
6578
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006579void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 if (ATRACE_ENABLED()) {
6581 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006582 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6583 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584 }
6585}
6586
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006587void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 if (ATRACE_ENABLED()) {
6589 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006590 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6591 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 }
6593}
6594
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006595void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006596 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006598 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006599 dumpDispatchStateLocked(dump);
6600
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006601 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006602 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006603 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 }
6605}
6606
6607void InputDispatcher::monitor() {
6608 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006609 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006611 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006612}
6613
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006614/**
6615 * Wake up the dispatcher and wait until it processes all events and commands.
6616 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6617 * this method can be safely called from any thread, as long as you've ensured that
6618 * the work you are interested in completing has already been queued.
6619 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006620bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006621 /**
6622 * Timeout should represent the longest possible time that a device might spend processing
6623 * events and commands.
6624 */
6625 constexpr std::chrono::duration TIMEOUT = 100ms;
6626 std::unique_lock lock(mLock);
6627 mLooper->wake();
6628 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6629 return result == std::cv_status::no_timeout;
6630}
6631
Vishnu Naire798b472020-07-23 13:52:21 -07006632/**
6633 * Sets focus to the window identified by the token. This must be called
6634 * after updating any input window handles.
6635 *
6636 * Params:
6637 * request.token - input channel token used to identify the window that should gain focus.
6638 * request.focusedToken - the token that the caller expects currently to be focused. If the
6639 * specified token does not match the currently focused window, this request will be dropped.
6640 * If the specified focused token matches the currently focused window, the call will succeed.
6641 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6642 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6643 * when requesting the focus change. This determines which request gets
6644 * precedence if there is a focus change request from another source such as pointer down.
6645 */
Vishnu Nair958da932020-08-21 17:12:37 -07006646void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6647 { // acquire lock
6648 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006649 std::optional<FocusResolver::FocusChanges> changes =
6650 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6651 if (changes) {
6652 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006653 }
6654 } // release lock
6655 // Wake up poll loop since it may need to make new input dispatching choices.
6656 mLooper->wake();
6657}
6658
Vishnu Nairc519ff72021-01-21 08:23:08 -08006659void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6660 if (changes.oldFocus) {
6661 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006662 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006663 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006664 "focus left window");
6665 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006666 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006667 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006668 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006669 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006670 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006671 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006672 }
6673
Prabir Pradhan99987712020-11-10 18:43:05 -08006674 // If a window has pointer capture, then it must have focus. We need to ensure that this
6675 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6676 // If the window loses focus before it loses pointer capture, then the window can be in a state
6677 // where it has pointer capture but not focus, violating the contract. Therefore we must
6678 // dispatch the pointer capture event before the focus event. Since focus events are added to
6679 // the front of the queue (above), we add the pointer capture event to the front of the queue
6680 // after the focus events are added. This ensures the pointer capture event ends up at the
6681 // front.
6682 disablePointerCaptureForcedLocked();
6683
Vishnu Nairc519ff72021-01-21 08:23:08 -08006684 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006685 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006686 }
6687}
Vishnu Nair958da932020-08-21 17:12:37 -07006688
Prabir Pradhan99987712020-11-10 18:43:05 -08006689void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006690 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006691 return;
6692 }
6693
6694 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6695
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006696 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006697 setPointerCaptureLocked(false);
6698 }
6699
6700 if (!mWindowTokenWithPointerCapture) {
6701 // No need to send capture changes because no window has capture.
6702 return;
6703 }
6704
6705 if (mPendingEvent != nullptr) {
6706 // Move the pending event to the front of the queue. This will give the chance
6707 // for the pending event to be dropped if it is a captured event.
6708 mInboundQueue.push_front(mPendingEvent);
6709 mPendingEvent = nullptr;
6710 }
6711
6712 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006713 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006714 mInboundQueue.push_front(std::move(entry));
6715}
6716
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006717void InputDispatcher::setPointerCaptureLocked(bool enable) {
6718 mCurrentPointerCaptureRequest.enable = enable;
6719 mCurrentPointerCaptureRequest.seq++;
6720 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006721 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006722 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006723 };
6724 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006725}
6726
Vishnu Nair599f1412021-06-21 10:39:58 -07006727void InputDispatcher::displayRemoved(int32_t displayId) {
6728 { // acquire lock
6729 std::scoped_lock _l(mLock);
6730 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006731 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006732 setFocusedApplicationLocked(displayId, nullptr);
6733 // Call focus resolver to clean up stale requests. This must be called after input windows
6734 // have been removed for the removed display.
6735 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006736 // Reset pointer capture eligibility, regardless of previous state.
6737 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006738 // Remove the associated touch mode state.
6739 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006740 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006741 } // release lock
6742
6743 // Wake up poll loop since it may need to make new input dispatching choices.
6744 mLooper->wake();
6745}
6746
Patrick Williamsd828f302023-04-28 17:52:08 -05006747void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006748 // The listener sends the windows as a flattened array. Separate the windows by display for
6749 // more convenient parsing.
6750 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006751 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006752 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006753 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006754 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006755
6756 { // acquire lock
6757 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006758
6759 // Ensure that we have an entry created for all existing displays so that if a displayId has
6760 // no windows, we can tell that the windows were removed from the display.
6761 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6762 handlesPerDisplay[displayId];
6763 }
6764
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006765 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006766 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006767 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6768 }
6769
6770 for (const auto& [displayId, handles] : handlesPerDisplay) {
6771 setInputWindowsLocked(handles, displayId);
6772 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006773
6774 if (update.vsyncId < mWindowInfosVsyncId) {
6775 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6776 ", current update vsync id: %" PRId64,
6777 mWindowInfosVsyncId, update.vsyncId);
6778 }
6779 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006780 }
6781 // Wake up poll loop since it may need to make new input dispatching choices.
6782 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006783}
6784
Vishnu Nair062a8672021-09-03 16:07:44 -07006785bool InputDispatcher::shouldDropInput(
6786 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006787 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6788 (windowHandle->getInfo()->inputConfig.test(
6789 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006790 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006791 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6792 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006793 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006794 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006795 windowHandle->getInfo()->displayId);
6796 return true;
6797 }
6798 return false;
6799}
6800
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006801void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006802 const gui::WindowInfosUpdate& update) {
6803 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006804}
6805
Arthur Hungdfd528e2021-12-08 13:23:04 +00006806void InputDispatcher::cancelCurrentTouch() {
6807 {
6808 std::scoped_lock _l(mLock);
6809 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006810 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006811 "cancel current touch");
6812 synthesizeCancelationEventsForAllConnectionsLocked(options);
6813
6814 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006815 }
6816 // Wake up poll loop since there might be work to do.
6817 mLooper->wake();
6818}
6819
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006820void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6821 std::scoped_lock _l(mLock);
6822 mMonitorDispatchingTimeout = timeout;
6823}
6824
Arthur Hungc539dbb2022-12-08 07:45:36 +00006825void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6826 const sp<WindowInfoHandle>& oldWindowHandle,
6827 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006828 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006829 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006830 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6831 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006832 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6833 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6834 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6835 newWindowHandle->getInfo()->inputConfig.test(
6836 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6837 const sp<WindowInfoHandle> oldWallpaper =
6838 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6839 const sp<WindowInfoHandle> newWallpaper =
6840 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6841 if (oldWallpaper == newWallpaper) {
6842 return;
6843 }
6844
6845 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006846 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006847 addPointerWindowTargetLocked(oldWallpaper,
6848 oldTouchedWindow.targetFlags |
6849 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6850 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId),
6851 targets);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006852 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006853 }
6854
6855 if (newWallpaper != nullptr) {
6856 state.addOrUpdateWindow(newWallpaper,
6857 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6858 InputTarget::Flags::WINDOW_IS_OBSCURED |
6859 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006860 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006861 }
6862}
6863
6864void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6865 ftl::Flags<InputTarget::Flags> newTargetFlags,
6866 const sp<WindowInfoHandle> fromWindowHandle,
6867 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006868 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006869 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006870 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6871 fromWindowHandle->getInfo()->inputConfig.test(
6872 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6873 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6874 toWindowHandle->getInfo()->inputConfig.test(
6875 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6876
6877 const sp<WindowInfoHandle> oldWallpaper =
6878 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6879 const sp<WindowInfoHandle> newWallpaper =
6880 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6881 if (oldWallpaper == newWallpaper) {
6882 return;
6883 }
6884
6885 if (oldWallpaper != nullptr) {
6886 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6887 "transferring touch focus to another window");
6888 state.removeWindowByToken(oldWallpaper->getToken());
6889 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6890 }
6891
6892 if (newWallpaper != nullptr) {
6893 nsecs_t downTimeInTarget = now();
6894 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6895 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6896 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6897 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006898 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6899 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006900 std::shared_ptr<Connection> wallpaperConnection =
6901 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006902 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006903 std::shared_ptr<Connection> toConnection =
6904 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006905 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6906 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6907 wallpaperFlags);
6908 }
6909 }
6910}
6911
6912sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6913 const sp<WindowInfoHandle>& windowHandle) const {
6914 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6915 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6916 bool foundWindow = false;
6917 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6918 if (!foundWindow && otherHandle != windowHandle) {
6919 continue;
6920 }
6921 if (windowHandle == otherHandle) {
6922 foundWindow = true;
6923 continue;
6924 }
6925
6926 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6927 return otherHandle;
6928 }
6929 }
6930 return nullptr;
6931}
6932
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006933void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6934 std::scoped_lock _l(mLock);
6935
6936 mConfig.keyRepeatTimeout = timeout;
6937 mConfig.keyRepeatDelay = delay;
6938}
6939
Garfield Tane84e6f92019-08-29 17:28:41 -07006940} // namespace android::inputdispatcher