blob: 47b9a0c62f152a389e73686c7dc79270c25302a6 [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.
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700954 bool isAppSwitchDue;
955 if (!input_flags::remove_app_switch_drops()) {
956 isAppSwitchDue = mAppSwitchDueTime <= currentTime;
957 if (mAppSwitchDueTime < *nextWakeupTime) {
958 *nextWakeupTime = mAppSwitchDueTime;
959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 }
961
962 // Ready to start a new event.
963 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700965 if (mInboundQueue.empty()) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700966 if (!input_flags::remove_app_switch_drops()) {
967 if (isAppSwitchDue) {
968 // The inbound queue is empty so the app switch key we were waiting
969 // for will never arrive. Stop waiting for it.
970 resetPendingAppSwitchLocked(false);
971 isAppSwitchDue = false;
972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 }
974
975 // Synthesize a key repeat if appropriate.
976 if (mKeyRepeatState.lastKeyEntry) {
977 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
978 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
979 } else {
980 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
981 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
982 }
983 }
984 }
985
986 // Nothing to do if there is no pending event.
987 if (!mPendingEvent) {
988 return;
989 }
990 } else {
991 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700992 mPendingEvent = mInboundQueue.front();
993 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 traceInboundQueueLengthLocked();
995 }
996
997 // Poke user activity for this event.
998 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 // Now we have an event to dispatch.
1004 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013
1014 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001019 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 const ConfigurationChangedEntry& typedEntry =
1021 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 break;
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001027 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 const DeviceResetEntry& typedEntry =
1029 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 break;
1033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001036 std::shared_ptr<FocusEntry> typedEntry =
1037 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001038 dispatchFocusLocked(currentTime, typedEntry);
1039 done = true;
1040 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1041 break;
1042 }
1043
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001044 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1045 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1046 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1047 done = true;
1048 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1049 break;
1050 }
1051
Prabir Pradhan99987712020-11-10 18:43:05 -08001052 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1053 const auto typedEntry =
1054 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1055 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1056 done = true;
1057 break;
1058 }
1059
arthurhungb89ccb02020-12-30 16:19:01 +08001060 case EventEntry::Type::DRAG: {
1061 std::shared_ptr<DragEntry> typedEntry =
1062 std::static_pointer_cast<DragEntry>(mPendingEvent);
1063 dispatchDragLocked(currentTime, typedEntry);
1064 done = true;
1065 break;
1066 }
1067
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001070 if (!input_flags::remove_app_switch_drops()) {
1071 if (isAppSwitchDue) {
1072 if (isAppSwitchKeyEvent(*keyEntry)) {
1073 resetPendingAppSwitchLocked(true);
1074 isAppSwitchDue = false;
1075 } else if (dropReason == DropReason::NOT_DROPPED) {
1076 dropReason = DropReason::APP_SWITCH;
1077 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 }
1079 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001080 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1084 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001086 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 break;
1088 }
1089
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001090 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001091 std::shared_ptr<MotionEntry> motionEntry =
1092 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001093 if (!input_flags::remove_app_switch_drops()) {
1094 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1095 dropReason = DropReason::APP_SWITCH;
1096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001098 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001101 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1102 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001104 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 }
Chris Yef59a2f42020-10-16 12:55:26 -07001107
1108 case EventEntry::Type::SENSOR: {
1109 std::shared_ptr<SensorEntry> sensorEntry =
1110 std::static_pointer_cast<SensorEntry>(mPendingEvent);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001111 if (!input_flags::remove_app_switch_drops()) {
1112 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1113 dropReason = DropReason::APP_SWITCH;
1114 }
Chris Yef59a2f42020-10-16 12:55:26 -07001115 }
1116 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1117 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1118 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1119 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1120 dropReason = DropReason::STALE;
1121 }
1122 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1123 done = true;
1124 break;
1125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
1127
1128 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001130 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
Michael Wright3a981722015-06-10 15:26:13 +01001132 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133
1134 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001135 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
1137}
1138
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001139bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001140 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001141}
1142
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001143/**
1144 * Return true if the events preceding this incoming motion event should be dropped
1145 * Return false otherwise (the default behaviour)
1146 */
1147bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001148 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001149 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001150
1151 // Optimize case where the current application is unresponsive and the user
1152 // decides to touch a window in a different application.
1153 // If the application takes too long to catch up then we drop all events preceding
1154 // the touch into the other window.
1155 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001156 const int32_t displayId = motionEntry.displayId;
1157 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001158 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001159
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001160 sp<WindowInfoHandle> touchedWindowHandle =
1161 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001162 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001163 touchedWindowHandle->getApplicationToken() !=
1164 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001165 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001166 ALOGI("Pruning input queue because user touched a different application while waiting "
1167 "for %s",
1168 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001169 return true;
1170 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001171
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001172 // Alternatively, maybe there's a spy window that could handle this event.
1173 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1174 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1175 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001176 const std::shared_ptr<Connection> connection =
1177 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001178 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001179 // This spy window could take more input. Drop all events preceding this
1180 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001181 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001182 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001183 mAwaitedFocusedApplication->getName().c_str());
1184 return true;
1185 }
1186 }
1187 }
1188
1189 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1190 // yet been processed by some connections, the dispatcher will wait for these motion
1191 // events to be processed before dispatching the key event. This is because these motion events
1192 // may cause a new window to be launched, which the user might expect to receive focus.
1193 // To prevent waiting forever for such events, just send the key to the currently focused window
1194 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1195 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1196 "just send the pending key event to the focused window.");
1197 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001198 }
1199 return false;
1200}
1201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204 mInboundQueue.push_back(std::move(newEntry));
1205 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 traceInboundQueueLengthLocked();
1207
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001208 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001209 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001210 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1211 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 // Optimize app switch latency.
1213 // If the application takes too long to catch up then we drop all events preceding
1214 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001216
1217 if (!input_flags::remove_app_switch_drops()) {
1218 if (isAppSwitchKeyEvent(keyEntry)) {
1219 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
1220 mAppSwitchSawKeyDown = true;
1221 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
1222 if (mAppSwitchSawKeyDown) {
1223 if (DEBUG_APP_SWITCH) {
1224 ALOGD("App switch is pending!");
1225 }
1226 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
1227 mAppSwitchSawKeyDown = false;
1228 needWake = true;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001229 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001230 }
1231 }
1232 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001233 // If a new up event comes in, and the pending event with same key code has been asked
1234 // to try again later because of the policy. We have to reset the intercept key wake up
1235 // time for it may have been handled in the policy and could be dropped.
1236 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1237 mPendingEvent->type == EventEntry::Type::KEY) {
1238 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1239 if (pendingKey.keyCode == keyEntry.keyCode &&
1240 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001241 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1242 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001243 pendingKey.interceptKeyWakeupTime = 0;
1244 needWake = true;
1245 }
1246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 break;
1248 }
1249
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001250 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001251 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1252 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1254 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001255 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001259 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001260 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1261 break;
1262 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001263 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001264 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001265 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001266 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001267 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1268 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001269 // nothing to do
1270 break;
1271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273
1274 return needWake;
1275}
1276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001278 // Do not store sensor event in recent queue to avoid flooding the queue.
1279 if (entry->type != EventEntry::Type::SENSOR) {
1280 mRecentQueue.push_back(entry);
1281 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001282 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001283 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285}
1286
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001287sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1288 bool isStylus,
1289 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001291 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001292 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001293 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001294 continue;
1295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001297 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001298 if (!info.isSpy() &&
1299 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001300 return windowHandle;
1301 }
1302 }
1303 return nullptr;
1304}
1305
1306std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001307 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001308 if (touchedWindow == nullptr) {
1309 return {};
1310 }
1311 // Traverse windows from front to back until we encounter the touched window.
1312 std::vector<InputTarget> outsideTargets;
1313 const auto& windowHandles = getWindowHandlesLocked(displayId);
1314 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1315 if (windowHandle == touchedWindow) {
1316 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1317 // below the touched window will not get ACTION_OUTSIDE event.
1318 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001319 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001320
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001321 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001322 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001323 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1324 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001325 addPointerWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1326 pointerIds,
1327 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 }
1329 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001330 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331}
1332
Prabir Pradhand65552b2021-10-07 11:23:50 -07001333std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001334 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001335 // Traverse windows from front to back and gather the touched spy windows.
1336 std::vector<sp<WindowInfoHandle>> spyWindows;
1337 const auto& windowHandles = getWindowHandlesLocked(displayId);
1338 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1339 const WindowInfo& info = *windowHandle->getInfo();
1340
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001341 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001342 continue;
1343 }
1344 if (!info.isSpy()) {
1345 // The first touched non-spy window was found, so return the spy windows touched so far.
1346 return spyWindows;
1347 }
1348 spyWindows.push_back(windowHandle);
1349 }
1350 return spyWindows;
1351}
1352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001353void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 const char* reason;
1355 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001356 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001357 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001358 ALOGD("Dropped event because policy consumed it.");
1359 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360 reason = "inbound event was dropped because the policy consumed it";
1361 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001362 case DropReason::DISABLED:
1363 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001364 ALOGI("Dropped event because input dispatch is disabled.");
1365 }
1366 reason = "inbound event was dropped because input dispatch is disabled";
1367 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001368 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001369 ALOGI("Dropped event because of pending overdue app switch.");
1370 reason = "inbound event was dropped because of pending overdue app switch";
1371 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001372 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373 ALOGI("Dropped event because the current application is not responding and the user "
1374 "has started interacting with a different application.");
1375 reason = "inbound event was dropped because the current application is not responding "
1376 "and the user has started interacting with a different application";
1377 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001379 ALOGI("Dropped event because it is stale.");
1380 reason = "inbound event was dropped because it is stale";
1381 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001382 case DropReason::NO_POINTER_CAPTURE:
1383 ALOGI("Dropped event because there is no window with Pointer Capture.");
1384 reason = "inbound event was dropped because there is no window with Pointer Capture";
1385 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001386 case DropReason::NOT_DROPPED: {
1387 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
1391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001393 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001394 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001398 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1400 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001401 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 synthesizeCancelationEventsForAllConnectionsLocked(options);
1403 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001404 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1405 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001406 synthesizeCancelationEventsForAllConnectionsLocked(options);
1407 }
1408 break;
1409 }
Chris Yef59a2f42020-10-16 12:55:26 -07001410 case EventEntry::Type::SENSOR: {
1411 break;
1412 }
arthurhungb89ccb02020-12-30 16:19:01 +08001413 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1414 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001415 break;
1416 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001417 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001418 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001419 case EventEntry::Type::CONFIGURATION_CHANGED:
1420 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001421 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001422 break;
1423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425}
1426
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001427static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1429 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430}
1431
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001432bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1433 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1434 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1435 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436}
1437
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001438bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001439 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440}
1441
1442void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001443 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001445 if (DEBUG_APP_SWITCH) {
1446 if (handled) {
1447 ALOGD("App switch has arrived.");
1448 } else {
1449 ALOGD("App switch was abandoned.");
1450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452}
1453
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001455 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456}
1457
Prabir Pradhancef936d2021-07-21 16:17:52 +00001458bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001459 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 return false;
1461 }
1462
1463 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001464 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001465 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001466 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1467 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 return true;
1470}
1471
Prabir Pradhancef936d2021-07-21 16:17:52 +00001472void InputDispatcher::postCommandLocked(Command&& command) {
1473 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474}
1475
1476void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001477 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001478 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001479 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 releaseInboundEventLocked(entry);
1481 }
1482 traceInboundQueueLengthLocked();
1483}
1484
1485void InputDispatcher::releasePendingEventLocked() {
1486 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 }
1490}
1491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001492void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001494 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001495 if (DEBUG_DISPATCH_CYCLE) {
1496 ALOGD("Injected inbound event was dropped.");
1497 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001498 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001501 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504}
1505
1506void InputDispatcher::resetKeyRepeatLocked() {
1507 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001508 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510}
1511
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001512std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1513 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514
Michael Wright2e732952014-09-24 13:26:59 -07001515 uint32_t policyFlags = entry->policyFlags &
1516 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 std::shared_ptr<KeyEntry> newEntry =
1519 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1520 entry->source, entry->displayId, policyFlags, entry->action,
1521 entry->flags, entry->keyCode, entry->scanCode,
1522 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001524 newEntry->syntheticRepeat = true;
1525 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528}
1529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001530bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001532 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1533 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
1536 // Reset key repeating in case a keyboard device was added or removed or something.
1537 resetKeyRepeatLocked();
1538
1539 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001540 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1541 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001542 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001543 };
1544 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 return true;
1546}
1547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1549 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001550 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1551 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1552 entry.deviceId);
1553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554
liushenxiang42232912021-05-21 20:24:09 +08001555 // Reset key repeating in case a keyboard device was disabled or enabled.
1556 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1557 resetKeyRepeatLocked();
1558 }
1559
Michael Wrightfb04fd52022-11-24 22:31:11 +00001560 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001561 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001563
1564 // Remove all active pointers from this device
1565 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1566 touchState.removeAllPointersForDevice(entry.deviceId);
1567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 return true;
1569}
1570
Vishnu Nairad321cd2020-08-20 16:40:21 -07001571void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001572 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001573 if (mPendingEvent != nullptr) {
1574 // Move the pending event to the front of the queue. This will give the chance
1575 // for the pending event to get dispatched to the newly focused window
1576 mInboundQueue.push_front(mPendingEvent);
1577 mPendingEvent = nullptr;
1578 }
1579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 std::unique_ptr<FocusEntry> focusEntry =
1581 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1582 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001583
1584 // This event should go to the front of the queue, but behind all other focus events
1585 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001586 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001587 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 [](const std::shared_ptr<EventEntry>& event) {
1589 return event->type == EventEntry::Type::FOCUS;
1590 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001591
1592 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001594}
1595
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001596void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001597 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001598 if (channel == nullptr) {
1599 return; // Window has gone away
1600 }
1601 InputTarget target;
1602 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001603 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001604 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001605 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1606 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001607 std::string reason = std::string("reason=").append(entry->reason);
1608 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001609 dispatchEventLocked(currentTime, entry, {target});
1610}
1611
Prabir Pradhan99987712020-11-10 18:43:05 -08001612void InputDispatcher::dispatchPointerCaptureChangedLocked(
1613 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1614 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001615 dropReason = DropReason::NOT_DROPPED;
1616
Prabir Pradhan99987712020-11-10 18:43:05 -08001617 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001618 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001619
1620 if (entry->pointerCaptureRequest.enable) {
1621 // Enable Pointer Capture.
1622 if (haveWindowWithPointerCapture &&
1623 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001624 // This can happen if pointer capture is disabled and re-enabled before we notify the
1625 // app of the state change, so there is no need to notify the app.
1626 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1627 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001628 }
1629 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001630 // This can happen if a window requests capture and immediately releases capture.
1631 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001632 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001633 return;
1634 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001635 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1636 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1637 return;
1638 }
1639
Vishnu Nairc519ff72021-01-21 08:23:08 -08001640 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001641 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1642 mWindowTokenWithPointerCapture = token;
1643 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001644 // Disable Pointer Capture.
1645 // We do not check if the sequence number matches for requests to disable Pointer Capture
1646 // for two reasons:
1647 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1648 // to disable capture with the same sequence number: one generated by
1649 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1650 // Capture being disabled in InputReader.
1651 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1652 // actual Pointer Capture state that affects events being generated by input devices is
1653 // in InputReader.
1654 if (!haveWindowWithPointerCapture) {
1655 // Pointer capture was already forcefully disabled because of focus change.
1656 dropReason = DropReason::NOT_DROPPED;
1657 return;
1658 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001659 token = mWindowTokenWithPointerCapture;
1660 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001661 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001662 setPointerCaptureLocked(false);
1663 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 }
1665
1666 auto channel = getInputChannelLocked(token);
1667 if (channel == nullptr) {
1668 // Window has gone away, clean up Pointer Capture state.
1669 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001670 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001671 setPointerCaptureLocked(false);
1672 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001673 return;
1674 }
1675 InputTarget target;
1676 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001677 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001678 entry->dispatchInProgress = true;
1679 dispatchEventLocked(currentTime, entry, {target});
1680
1681 dropReason = DropReason::NOT_DROPPED;
1682}
1683
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001684void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1685 const std::shared_ptr<TouchModeEntry>& entry) {
1686 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001687 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001688 if (windowHandles.empty()) {
1689 return;
1690 }
1691 const std::vector<InputTarget> inputTargets =
1692 getInputTargetsFromWindowHandlesLocked(windowHandles);
1693 if (inputTargets.empty()) {
1694 return;
1695 }
1696 entry->dispatchInProgress = true;
1697 dispatchEventLocked(currentTime, entry, inputTargets);
1698}
1699
1700std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1701 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1702 std::vector<InputTarget> inputTargets;
1703 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001704 const sp<IBinder>& token = handle->getToken();
1705 if (token == nullptr) {
1706 continue;
1707 }
1708 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1709 if (channel == nullptr) {
1710 continue; // Window has gone away
1711 }
1712 InputTarget target;
1713 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001714 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001715 inputTargets.push_back(target);
1716 }
1717 return inputTargets;
1718}
1719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001720bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001721 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001723 if (!entry->dispatchInProgress) {
1724 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1725 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1726 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1727 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001728 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 // We have seen two identical key downs in a row which indicates that the device
1730 // driver is automatically generating key repeats itself. We take note of the
1731 // repeat here, but we disable our own next key repeat timer since it is clear that
1732 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001733 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1734 // Make sure we don't get key down from a different device. If a different
1735 // device Id has same key pressed down, the new device Id will replace the
1736 // current one to hold the key repeat with repeat count reset.
1737 // In the future when got a KEY_UP on the device id, drop it and do not
1738 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1740 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001741 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 } else {
1743 // Not a repeat. Save key down state in case we do see a repeat later.
1744 resetKeyRepeatLocked();
1745 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1746 }
1747 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001748 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1749 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001750 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001751 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001752 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1753 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 resetKeyRepeatLocked();
1756 }
1757
1758 if (entry->repeatCount == 1) {
1759 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1760 } else {
1761 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1762 }
1763
1764 entry->dispatchInProgress = true;
1765
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001766 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768
1769 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001770 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 if (currentTime < entry->interceptKeyWakeupTime) {
1772 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1773 *nextWakeupTime = entry->interceptKeyWakeupTime;
1774 }
1775 return false; // wait until next wakeup
1776 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001777 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 entry->interceptKeyWakeupTime = 0;
1779 }
1780
1781 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001782 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001784 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001785 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001786
1787 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1788 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1789 };
1790 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001791 // Poke user activity for keys not passed to user
1792 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 return false; // wait for the command to run
1794 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001795 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001797 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001798 if (*dropReason == DropReason::NOT_DROPPED) {
1799 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 }
1801 }
1802
1803 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001804 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001805 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1807 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001808 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001809 // Poke user activity for undispatched keys
1810 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 return true;
1812 }
1813
1814 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001815 InputEventInjectionResult injectionResult;
1816 sp<WindowInfoHandle> focusedWindow =
1817 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1818 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001819 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 return false;
1821 }
1822
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001823 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001824 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 return true;
1826 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001827 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1828
1829 std::vector<InputTarget> inputTargets;
1830 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001831 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001832 getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001834 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836
1837 // Dispatch the key.
1838 dispatchEventLocked(currentTime, entry, inputTargets);
1839 return true;
1840}
1841
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001842void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001843 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1844 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1845 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1846 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1847 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1848 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1849 entry.metaState, entry.repeatCount, entry.downTime);
1850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851}
1852
Prabir Pradhancef936d2021-07-21 16:17:52 +00001853void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1854 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001855 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001856 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1857 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1858 "source=0x%x, sensorType=%s",
1859 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001860 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001861 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001862 auto command = [this, entry]() REQUIRES(mLock) {
1863 scoped_unlock unlock(mLock);
1864
1865 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001866 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001867 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001868 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1869 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001870 };
1871 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001872}
1873
1874bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001875 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1876 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001877 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001878 }
Chris Yef59a2f42020-10-16 12:55:26 -07001879 { // acquire lock
1880 std::scoped_lock _l(mLock);
1881
1882 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1883 std::shared_ptr<EventEntry> entry = *it;
1884 if (entry->type == EventEntry::Type::SENSOR) {
1885 it = mInboundQueue.erase(it);
1886 releaseInboundEventLocked(entry);
1887 }
1888 }
1889 }
1890 return true;
1891}
1892
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001893bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001894 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001895 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001897 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 entry->dispatchInProgress = true;
1899
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001900 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
1902
1903 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001904 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001905 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1907 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 return true;
1909 }
1910
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001911 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912
1913 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001914 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 if (isPointerEvent) {
1918 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001919
1920 if (mDragState &&
1921 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1922 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1923 pilferPointersLocked(mDragState->dragWindow->getToken());
1924 }
1925
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001926 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001927 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001928 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1929 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 } else {
1931 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001932 sp<WindowInfoHandle> focusedWindow =
1933 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1934 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1935 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1936 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001937 InputTarget::Flags::FOREGROUND |
1938 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001939 getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 return false;
1944 }
1945
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001946 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001947 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001948 return true;
1949 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001951 CancelationOptions::Mode mode(
1952 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1953 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001954 CancelationOptions options(mode, "input event injection failed");
1955 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 return true;
1957 }
1958
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001959 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001960 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961
1962 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 dispatchEventLocked(currentTime, entry, inputTargets);
1964 return true;
1965}
1966
chaviw98318de2021-05-19 16:45:23 -05001967void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001968 bool isExiting, const int32_t rawX,
1969 const int32_t rawY) {
1970 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001971 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001972 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1973 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001974
1975 enqueueInboundEventLocked(std::move(dragEntry));
1976}
1977
1978void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1979 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1980 if (channel == nullptr) {
1981 return; // Window has gone away
1982 }
1983 InputTarget target;
1984 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001985 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001986 entry->dispatchInProgress = true;
1987 dispatchEventLocked(currentTime, entry, {target});
1988}
1989
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001990void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001992 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001993 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001994 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001995 "metaState=0x%x, buttonState=0x%x,"
1996 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001997 prefix, entry.eventTime, entry.deviceId,
1998 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1999 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2000 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2001 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002003 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002004 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002005 "x=%f, y=%f, pressure=%f, size=%f, "
2006 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2007 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002008 i, entry.pointerProperties[i].id,
2009 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2015 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2016 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2017 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2018 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021}
2022
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002023void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2024 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002026 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002027 if (DEBUG_DISPATCH_CYCLE) {
2028 ALOGD("dispatchEventToCurrentInputTargets");
2029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002031 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002032
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2034
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002035 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002037 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002038 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002039 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002040 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002041 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002043 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2044 LOG(INFO) << "Dropping event delivery to target with channel "
2045 << inputTarget.inputChannel->getName()
2046 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
2049 }
2050}
2051
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002052void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2054 // If the policy decides to close the app, we will get a channel removal event via
2055 // unregisterInputChannel, and will clean up the connection that way. We are already not
2056 // sending new pointers to the connection when it blocked, but focused events will continue to
2057 // pile up.
2058 ALOGW("Canceling events for %s because it is unresponsive",
2059 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002060 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002061 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002062 "application not responding");
2063 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065}
2066
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002068 if (DEBUG_FOCUS) {
2069 ALOGD("Resetting ANR timeouts.");
2070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
2072 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002073 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002074 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075}
2076
Tiger Huang721e26f2018-07-24 22:26:19 +08002077/**
2078 * Get the display id that the given event should go to. If this event specifies a valid display id,
2079 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2080 * Focused display is the display that the user most recently interacted with.
2081 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002083 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002084 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002085 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2087 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002088 break;
2089 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002090 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002091 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2092 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002093 break;
2094 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002095 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002096 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002097 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002098 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002099 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002100 case EventEntry::Type::SENSOR:
2101 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002102 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002103 return ADISPLAY_ID_NONE;
2104 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002105 }
2106 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2107}
2108
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2110 const char* focusedWindowName) {
2111 if (mAnrTracker.empty()) {
2112 // already processed all events that we waited for
2113 mKeyIsWaitingForEventsTimeout = std::nullopt;
2114 return false;
2115 }
2116
2117 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2118 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002119 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002120 mKeyIsWaitingForEventsTimeout = currentTime +
2121 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2122 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002123 return true;
2124 }
2125
2126 // We still have pending events, and already started the timer
2127 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2128 return true; // Still waiting
2129 }
2130
2131 // Waited too long, and some connection still hasn't processed all motions
2132 // Just send the key to the focused window
2133 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2134 focusedWindowName);
2135 mKeyIsWaitingForEventsTimeout = std::nullopt;
2136 return false;
2137}
2138
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002139sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2140 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2141 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002142 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002143 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144
Tiger Huang721e26f2018-07-24 22:26:19 +08002145 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002146 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002147 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002148 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2149
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 // If there is no currently focused window and no focused application
2151 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002152 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2153 ALOGI("Dropping %s event because there is no focused window or focused application in "
2154 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002155 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002156 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
2158
Vishnu Nair062a8672021-09-03 16:07:44 -07002159 // Drop key events if requested by input feature
2160 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002161 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002162 }
2163
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002164 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2165 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2166 // start interacting with another application via touch (app switch). This code can be removed
2167 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2168 // an app is expected to have a focused window.
2169 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2170 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2171 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002172 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2173 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2174 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002176 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177 ALOGW("Waiting because no window has focus but %s may eventually add a "
2178 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002179 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002180 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002181 outInjectionResult = InputEventInjectionResult::PENDING;
2182 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002183 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2184 // Already raised ANR. Drop the event
2185 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002186 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002187 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 } else {
2189 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002190 outInjectionResult = InputEventInjectionResult::PENDING;
2191 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002192 }
2193 }
2194
2195 // we have a valid, non-null focused window
2196 resetNoFocusedWindowTimeoutLocked();
2197
Prabir Pradhan5735a322022-04-11 17:23:34 +00002198 // Verify targeted injection.
2199 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2200 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002201 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2202 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 }
2204
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002205 if (focusedWindowHandle->getInfo()->inputConfig.test(
2206 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002207 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002208 outInjectionResult = InputEventInjectionResult::PENDING;
2209 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002210 }
2211
2212 // If the event is a key event, then we must wait for all previous events to
2213 // complete before delivering it because previous events may have the
2214 // side-effect of transferring focus to a different window and we want to
2215 // ensure that the following keys are sent to the new window.
2216 //
2217 // Suppose the user touches a button in a window then immediately presses "A".
2218 // If the button causes a pop-up window to appear then we want to ensure that
2219 // the "A" key is delivered to the new pop-up window. This is because users
2220 // often anticipate pending UI changes when typing on a keyboard.
2221 // To obtain this behavior, we must serialize key events with respect to all
2222 // prior input events.
2223 if (entry.type == EventEntry::Type::KEY) {
2224 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2225 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002226 outInjectionResult = InputEventInjectionResult::PENDING;
2227 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002231 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2232 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233}
2234
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002235/**
2236 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2237 * that are currently unresponsive.
2238 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002239std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2240 const std::vector<Monitor>& monitors) const {
2241 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002243 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002244 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002245 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 if (connection == nullptr) {
2247 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002248 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249 return false;
2250 }
2251 if (!connection->responsive) {
2252 ALOGW("Unresponsive monitor %s will not get the new gesture",
2253 connection->inputChannel->getName().c_str());
2254 return false;
2255 }
2256 return true;
2257 });
2258 return responsiveMonitors;
2259}
2260
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002261std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002262 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002263 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002264 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002266 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 // For security reasons, we defer updating the touch state until we are sure that
2268 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002269 const int32_t displayId = entry.displayId;
2270 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002271 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272
2273 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002274 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 // Copy current touch state into tempTouchState.
2277 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2278 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002279 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002281 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2282 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002283 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002284 }
2285
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002286 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002287
2288 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2289 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2290 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002291 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2292 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002293 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002294 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2295 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002296 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2297 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2298 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002299 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002300
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002301 if (newGesture) {
2302 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002303 }
2304
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002305 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2306 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2307 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002310 if (isHoverAction) {
2311 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2312 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002313 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002314 }
2315
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2317 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002318 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002319 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002320 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002321 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2322 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002323 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002324 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002325 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002326
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002327 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002328 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002331 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002332 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002334 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002335 }
2336
Prabir Pradhan5735a322022-04-11 17:23:34 +00002337 // Verify targeted injection.
2338 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2339 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002340 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002341 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002342 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002343 }
2344
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002345 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002346 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002347 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2348 // New window supports splitting, but we should never split mouse events.
2349 isSplit = !isFromMouse;
2350 } else if (isSplit) {
2351 // New window does not support splitting but we have already split events.
2352 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002353 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2354 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002355 newTouchedWindowHandle = nullptr;
2356 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002357 } else {
2358 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002359 // be delivered to a new window which supports split touch. Pointers from a mouse device
2360 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002361 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002362 }
2363
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002364 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002365 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002367 // Process the foreground window first so that it is the first to receive the event.
2368 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002369 }
2370
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002371 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002372 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2373 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002374 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002375 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002376 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377 }
2378
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002380 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002381 continue;
2382 }
2383
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002384 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002385 // The "windowHandle" is the target of this hovering pointer.
2386 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002387 }
2388
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002392 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2393 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002394 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002395 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002396
2397 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002398 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 }
2400 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002401 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002402 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002403 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002404 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002405
2406 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002407
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002408 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002409 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002410 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002411 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2412 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2413 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId,
2414 pointerIds,
2415 isDownOrPointerDown
2416 ? std::make_optional(entry.eventTime)
2417 : std::nullopt);
2418 // If this is the pointer going down and the touched window has a wallpaper
2419 // then also add the touched wallpaper windows so they are locked in for the
2420 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2421 // SCROLL because the wallpaper engine only supports touch events. We would need to
2422 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2423 // handle these events.
2424 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002425 windowHandle->getInfo()->inputConfig.test(
2426 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2427 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2428 if (wallpaper != nullptr) {
2429 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2430 InputTarget::Flags::WINDOW_IS_OBSCURED |
2431 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2432 InputTarget::Flags::DISPATCH_AS_IS;
2433 if (isSplit) {
2434 wallpaperFlags |= InputTarget::Flags::SPLIT;
2435 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002436 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2437 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002438 }
2439 }
2440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002442
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002443 // If a window is already pilfering some pointers, give it this new pointer as well and
2444 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2445 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002446 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002447 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2448 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002449 // This window is already pilfering some pointers, and this new pointer is also
2450 // going to it. Therefore, take over this pointer and don't give it to anyone
2451 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002452 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002453 }
2454 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002455
2456 // Restrict all pilfered pointers to the pilfering windows.
2457 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 } else {
2459 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2460
2461 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002462 if (!tempTouchState.isDown(entry.deviceId) &&
2463 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002464 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2465 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2466 << " is not down or we previously dropped the pointer down event in "
2467 << "display " << displayId << ": " << entry.getDescription();
2468 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002469 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002470 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
2472
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002473 // If the pointer is not currently hovering, then ignore the event.
2474 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2475 const int32_t pointerId = entry.pointerProperties[0].id;
2476 if (oldState == nullptr ||
2477 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2478 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2479 "display "
2480 << displayId << ": " << entry.getDescription();
2481 outInjectionResult = InputEventInjectionResult::FAILED;
2482 return {};
2483 }
2484 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2485 }
2486
arthurhung6d4bed92021-03-17 11:59:33 +08002487 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002490 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002491 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002492 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002493 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002494 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002495 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002496 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002497 sp<WindowInfoHandle> newTouchedWindowHandle =
2498 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002499
Prabir Pradhan5735a322022-04-11 17:23:34 +00002500 // Verify targeted injection.
2501 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2502 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002503 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002504 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002505 }
2506
Vishnu Nair062a8672021-09-03 16:07:44 -07002507 // Drop touch events if requested by input feature
2508 if (newTouchedWindowHandle != nullptr &&
2509 shouldDropInput(entry, newTouchedWindowHandle)) {
2510 newTouchedWindowHandle = nullptr;
2511 }
2512
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002513 if (newTouchedWindowHandle != nullptr &&
2514 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002515 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002516 oldTouchedWindowHandle->getName().c_str(),
2517 newTouchedWindowHandle->getName().c_str(), displayId);
2518
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002520 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002521 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002522 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002523
2524 const TouchedWindow& touchedWindow =
2525 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002526 addPointerWindowTargetLocked(oldTouchedWindowHandle,
2527 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
2528 pointerIds,
2529 touchedWindow.getDownTimeInTarget(entry.deviceId),
2530 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531
2532 // Make a slippery entrance into the new window.
2533 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002534 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 ftl::Flags<InputTarget::Flags> targetFlags =
2538 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002539 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002540 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002543 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
2545 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002546 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002547 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002548 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
2550
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002551 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2552 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002553
2554 // Check if the wallpaper window should deliver the corresponding event.
2555 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002556 tempTouchState, entry.deviceId, pointerId, targets);
2557 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2558 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560 }
Arthur Hung96483742022-11-15 03:30:48 +00002561
2562 // Update the pointerIds for non-splittable when it received pointer down.
2563 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2564 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002565 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002566 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2567 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2568 // Ignore drag window for it should just track one pointer.
2569 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2570 continue;
2571 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002572 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2573 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2574 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002575 }
2576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
2578
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002579 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002580 {
2581 std::vector<TouchedWindow> hoveringWindows =
2582 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2583 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002584 std::optional<InputTarget> target =
2585 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002586 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002587 if (!target) {
2588 continue;
2589 }
2590 // Hardcode to single hovering pointer for now.
2591 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2592 pointerIds.set(entry.pointerProperties[0].id);
2593 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2594 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597
Prabir Pradhan5735a322022-04-11 17:23:34 +00002598 // Ensure that all touched windows are valid for injection.
2599 if (entry.injectionState != nullptr) {
2600 std::string errs;
2601 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002602 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2603 if (err) errs += "\n - " + *err;
2604 }
2605 if (!errs.empty()) {
2606 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002607 "%s:%s",
2608 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002609 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002610 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002611 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002612 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002613
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002614 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2615 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002617 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002618 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002619 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002620 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002621 for (InputTarget& target : targets) {
2622 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2623 sp<WindowInfoHandle> targetWindow =
2624 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2625 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2626 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 }
2629 }
2630 }
2631 }
2632
Harry Cuttsb166c002023-05-09 13:06:05 +00002633 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2634 // only want the system UI to handle these gestures.
2635 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2636 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2637 if (isTouchpadNavGesture) {
2638 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2639 }
2640
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002641 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002642 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002643 std::bitset<MAX_POINTER_ID + 1> touchingPointers =
2644 touchedWindow.getTouchingPointers(entry.deviceId);
2645 if (touchingPointers.none()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002646 continue;
2647 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002648 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2649 touchingPointers,
2650 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002651 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002652
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002653 // During targeted injection, only allow owned targets to receive events
2654 std::erase_if(targets, [&](const InputTarget& target) {
2655 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2656 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2657 if (err) {
2658 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2659 << ": " << (*err);
2660 return true;
2661 }
2662 return false;
2663 });
2664
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002665 if (targets.empty()) {
2666 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2667 outInjectionResult = InputEventInjectionResult::FAILED;
2668 return {};
2669 }
2670
2671 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2672 // window that is actually receiving the entire gesture.
2673 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2674 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2675 })) {
2676 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2677 << entry.getDescription();
2678 outInjectionResult = InputEventInjectionResult::FAILED;
2679 return {};
2680 }
2681
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002682 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002684 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2685 // Targets that we entered in a slippery way will now become AS-IS targets
2686 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
2687 touchedWindow.targetFlags.clear(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
2688 touchedWindow.targetFlags |= InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002689 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002690 }
2691
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002692 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002693 if (isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002694 if (oldState && oldState->isDown(entry.deviceId)) {
2695 // Started hovering, but the device is already down: reject the hover event
2696 LOG(ERROR) << "Got hover event " << entry.getDescription()
2697 << " but the device is already down " << oldState->dump();
2698 outInjectionResult = InputEventInjectionResult::FAILED;
2699 return {};
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002700 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002701 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2702 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002703 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002704 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002706 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002707 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2708 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002709 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2710 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2711 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
2713
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 // Save changes unless the action was scroll in which case the temporary touch
2715 // state was only valid for this one action.
2716 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002717 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002718 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002719 mTouchStatesByDisplay[displayId] = tempTouchState;
2720 } else {
2721 mTouchStatesByDisplay.erase(displayId);
2722 }
2723 }
2724
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002725 if (tempTouchState.windows.empty()) {
2726 mTouchStatesByDisplay.erase(displayId);
2727 }
2728
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002729 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730}
2731
arthurhung6d4bed92021-03-17 11:59:33 +08002732void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002733 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2734 // have an explicit reason to support it.
2735 constexpr bool isStylus = false;
2736
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002737 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002738 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002739 if (dropWindow) {
2740 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002741 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002742 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002743 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002744 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002745 }
2746 mDragState.reset();
2747}
2748
2749void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002750 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002751 return;
2752 }
2753
arthurhung6d4bed92021-03-17 11:59:33 +08002754 if (!mDragState->isStartDrag) {
2755 mDragState->isStartDrag = true;
2756 mDragState->isStylusButtonDownAtStart =
2757 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2758 }
2759
Arthur Hung54745652022-04-20 07:17:41 +00002760 // Find the pointer index by id.
2761 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002762 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002763 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2764 if (pointerProperties.id == mDragState->pointerId) {
2765 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002766 }
Arthur Hung54745652022-04-20 07:17:41 +00002767 }
arthurhung6d4bed92021-03-17 11:59:33 +08002768
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002769 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002770 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002771 }
2772
2773 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2774 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2775 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2776
2777 switch (maskedAction) {
2778 case AMOTION_EVENT_ACTION_MOVE: {
2779 // Handle the special case : stylus button no longer pressed.
2780 bool isStylusButtonDown =
2781 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2782 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2783 finishDragAndDrop(entry.displayId, x, y);
2784 return;
2785 }
2786
2787 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2788 // until we have an explicit reason to support it.
2789 constexpr bool isStylus = false;
2790
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002791 sp<WindowInfoHandle> hoverWindowHandle =
2792 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2793 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002794 // enqueue drag exit if needed.
2795 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2796 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2797 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002798 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002799 y);
2800 }
2801 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2802 }
2803 // enqueue drag location if needed.
2804 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002805 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002806 }
2807 break;
2808 }
2809
2810 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002811 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002812 break;
2813 }
2814 // The drag pointer is up.
2815 [[fallthrough]];
2816 case AMOTION_EVENT_ACTION_UP:
2817 finishDragAndDrop(entry.displayId, x, y);
2818 break;
2819 case AMOTION_EVENT_ACTION_CANCEL: {
2820 ALOGD("Receiving cancel when drag and drop.");
2821 sendDropWindowCommandLocked(nullptr, 0, 0);
2822 mDragState.reset();
2823 break;
2824 }
arthurhungb89ccb02020-12-30 16:19:01 +08002825 }
2826}
2827
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002828std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2829 const sp<android::gui::WindowInfoHandle>& windowHandle,
2830 ftl::Flags<InputTarget::Flags> targetFlags,
2831 std::optional<nsecs_t> firstDownTimeInTarget) const {
2832 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2833 if (inputChannel == nullptr) {
2834 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2835 return {};
2836 }
2837 InputTarget inputTarget;
2838 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002839 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002840 inputTarget.flags = targetFlags;
2841 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2842 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2843 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2844 if (displayInfoIt != mDisplayInfos.end()) {
2845 inputTarget.displayTransform = displayInfoIt->second.transform;
2846 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002847 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002848 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2849 }
2850 return inputTarget;
2851}
2852
chaviw98318de2021-05-19 16:45:23 -05002853void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002854 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002855 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002856 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002857 std::vector<InputTarget>::iterator it =
2858 std::find_if(inputTargets.begin(), inputTargets.end(),
2859 [&windowHandle](const InputTarget& inputTarget) {
2860 return inputTarget.inputChannel->getConnectionToken() ==
2861 windowHandle->getToken();
2862 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002863
chaviw98318de2021-05-19 16:45:23 -05002864 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865
2866 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002867 std::optional<InputTarget> target =
2868 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2869 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 return;
2871 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002873 it = inputTargets.end() - 1;
2874 }
2875
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002876 if (it->flags != targetFlags) {
2877 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2878 }
2879 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2880 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2881 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2882 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002883}
2884
2885void InputDispatcher::addPointerWindowTargetLocked(
2886 const sp<android::gui::WindowInfoHandle>& windowHandle,
2887 ftl::Flags<InputTarget::Flags> targetFlags, std::bitset<MAX_POINTER_ID + 1> pointerIds,
2888 std::optional<nsecs_t> firstDownTimeInTarget, std::vector<InputTarget>& inputTargets) const
2889 REQUIRES(mLock) {
2890 if (pointerIds.none()) {
2891 for (const auto& target : inputTargets) {
2892 LOG(INFO) << "Target: " << target;
2893 }
2894 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2895 return;
2896 }
2897 std::vector<InputTarget>::iterator it =
2898 std::find_if(inputTargets.begin(), inputTargets.end(),
2899 [&windowHandle](const InputTarget& inputTarget) {
2900 return inputTarget.inputChannel->getConnectionToken() ==
2901 windowHandle->getToken();
2902 });
2903
2904 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2905 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2906 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2907 // input targets for hovering pointers and for touching pointers.
2908 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2909 // target instead.
2910 if (it != inputTargets.end() && it->flags.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
2911 // Force the code below to create a new input target
2912 it = inputTargets.end();
2913 }
2914
2915 const WindowInfo* windowInfo = windowHandle->getInfo();
2916
2917 if (it == inputTargets.end()) {
2918 std::optional<InputTarget> target =
2919 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2920 if (!target) {
2921 return;
2922 }
2923 inputTargets.push_back(*target);
2924 it = inputTargets.end() - 1;
2925 }
2926
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002927 if (it->flags != targetFlags) {
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002928 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002929 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002930 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2931 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2932 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2933 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002934
chaviw1ff3d1e2020-07-01 15:53:47 -07002935 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936}
2937
Michael Wright3dd60e22019-03-27 22:06:44 +00002938void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002939 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002940 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2941 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002942
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002943 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2944 InputTarget target;
2945 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002946 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002947 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2948 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002949 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2950 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002951 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002952 target.setDefaultPointerTransform(target.displayTransform);
2953 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 }
2955}
2956
Robert Carrc9bf1d32020-04-13 17:21:08 -07002957/**
2958 * Indicate whether one window handle should be considered as obscuring
2959 * another window handle. We only check a few preconditions. Actually
2960 * checking the bounds is left to the caller.
2961 */
chaviw98318de2021-05-19 16:45:23 -05002962static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2963 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002964 // Compare by token so cloned layers aren't counted
2965 if (haveSameToken(windowHandle, otherHandle)) {
2966 return false;
2967 }
2968 auto info = windowHandle->getInfo();
2969 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002970 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002971 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002972 } else if (otherInfo->alpha == 0 &&
2973 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002974 // Those act as if they were invisible, so we don't need to flag them.
2975 // We do want to potentially flag touchable windows even if they have 0
2976 // opacity, since they can consume touches and alter the effects of the
2977 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002978 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002979 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2980 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002981 } else if (info->ownerUid == otherInfo->ownerUid) {
2982 // If ownerUid is the same we don't generate occlusion events as there
2983 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002984 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002985 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002986 return false;
2987 } else if (otherInfo->displayId != info->displayId) {
2988 return false;
2989 }
2990 return true;
2991}
2992
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002993/**
2994 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2995 * untrusted, one should check:
2996 *
2997 * 1. If result.hasBlockingOcclusion is true.
2998 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2999 * BLOCK_UNTRUSTED.
3000 *
3001 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3002 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3003 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3004 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3005 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3006 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3007 *
3008 * If neither of those is true, then it means the touch can be allowed.
3009 */
3010InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003011 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3012 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003013 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003014 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003015 TouchOcclusionInfo info;
3016 info.hasBlockingOcclusion = false;
3017 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003018 info.obscuringUid = gui::Uid::INVALID;
3019 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003020 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003021 if (windowHandle == otherHandle) {
3022 break; // All future windows are below us. Exit early.
3023 }
chaviw98318de2021-05-19 16:45:23 -05003024 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003025 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3026 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003027 if (DEBUG_TOUCH_OCCLUSION) {
3028 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003029 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003030 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003031 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3032 // we perform the checks below to see if the touch can be propagated or not based on the
3033 // window's touch occlusion mode
3034 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3035 info.hasBlockingOcclusion = true;
3036 info.obscuringUid = otherInfo->ownerUid;
3037 info.obscuringPackage = otherInfo->packageName;
3038 break;
3039 }
3040 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003041 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003042 float opacity =
3043 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3044 // Given windows A and B:
3045 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3046 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3047 opacityByUid[uid] = opacity;
3048 if (opacity > info.obscuringOpacity) {
3049 info.obscuringOpacity = opacity;
3050 info.obscuringUid = uid;
3051 info.obscuringPackage = otherInfo->packageName;
3052 }
3053 }
3054 }
3055 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003056 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003057 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003058 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003059 return info;
3060}
3061
chaviw98318de2021-05-19 16:45:23 -05003062std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003063 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003064 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003065 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3066 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3067 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003068 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003069 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003070 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3071 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003072 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3073 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3074 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003075 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003076}
3077
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003078bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3079 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003080 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3081 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003082 return false;
3083 }
3084 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003085 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003086 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003087 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003088 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3089 return false;
3090 }
3091 return true;
3092}
3093
chaviw98318de2021-05-19 16:45:23 -05003094bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003097 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3098 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003099 if (windowHandle == otherHandle) {
3100 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
chaviw98318de2021-05-19 16:45:23 -05003102 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003103 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003104 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 return true;
3106 }
3107 }
3108 return false;
3109}
3110
chaviw98318de2021-05-19 16:45:23 -05003111bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003112 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003113 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3114 const WindowInfo* windowInfo = windowHandle->getInfo();
3115 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003116 if (windowHandle == otherHandle) {
3117 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003118 }
chaviw98318de2021-05-19 16:45:23 -05003119 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003120 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003121 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003122 return true;
3123 }
3124 }
3125 return false;
3126}
3127
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003128std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003129 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003130 if (applicationHandle != nullptr) {
3131 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003132 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 } else {
3134 return applicationHandle->getName();
3135 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003136 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003137 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003139 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
3141}
3142
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003143void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003144 if (!isUserActivityEvent(eventEntry)) {
3145 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003146 return;
3147 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003148 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003149 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003150 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003151 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003152 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003153 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003154 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 }
3156 }
3157
3158 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003159 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003160 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003161 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3162 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 return;
3164 }
Josep del Riob3981622023-04-18 15:49:45 +00003165 if (windowDisablingUserActivityInfo != nullptr) {
3166 if (DEBUG_DISPATCH_CYCLE) {
3167 ALOGD("Not poking user activity: disabled by window '%s'.",
3168 windowDisablingUserActivityInfo->name.c_str());
3169 }
3170 return;
3171 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003172 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003173 eventType = USER_ACTIVITY_EVENT_TOUCH;
3174 }
3175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003177 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003178 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3179 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 return;
3181 }
Josep del Riob3981622023-04-18 15:49:45 +00003182 // If the key code is unknown, we don't consider it user activity
3183 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3184 return;
3185 }
3186 // Don't inhibit events that were intercepted or are not passed to
3187 // the apps, like system shortcuts
3188 if (windowDisablingUserActivityInfo != nullptr &&
3189 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3190 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3191 if (DEBUG_DISPATCH_CYCLE) {
3192 ALOGD("Not poking user activity: disabled by window '%s'.",
3193 windowDisablingUserActivityInfo->name.c_str());
3194 }
3195 return;
3196 }
3197
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 eventType = USER_ACTIVITY_EVENT_BUTTON;
3199 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003201 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003202 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003203 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003204 break;
3205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
3207
Prabir Pradhancef936d2021-07-21 16:17:52 +00003208 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3209 REQUIRES(mLock) {
3210 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003211 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003212 };
3213 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214}
3215
3216void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003217 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003218 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003219 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003220 ATRACE_NAME_IF(ATRACE_ENABLED(),
3221 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3222 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003223 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003224 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003225 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003226 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003227 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003228 inputTarget.getPointerInfoString().c_str());
3229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230
3231 // Skip this event if the connection status is not normal.
3232 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003233 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003234 if (DEBUG_DISPATCH_CYCLE) {
3235 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003236 connection->getInputChannelName().c_str(),
3237 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 return;
3240 }
3241
3242 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003243 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003244 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003245 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003246 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003248 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003249 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003250 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3251 logDispatchStateLocked();
3252 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3253 "target on connection "
3254 << connection->getInputChannelName() << " for "
3255 << originalMotionEntry.getDescription();
3256 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003258 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3259 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260 if (!splitMotionEntry) {
3261 return; // split event was dropped
3262 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003263 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3264 std::string reason = std::string("reason=pointer cancel on split window");
3265 android_log_event_list(LOGTAG_INPUT_CANCEL)
3266 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3267 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003268 if (DEBUG_FOCUS) {
3269 ALOGD("channel '%s' ~ Split motion event.",
3270 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003271 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003272 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003273 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3274 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 return;
3276 }
3277 }
3278
3279 // Not splitting. Enqueue dispatch entries for the event as is.
3280 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3281}
3282
3283void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003284 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003286 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003287 ATRACE_NAME_IF(ATRACE_ENABLED(),
3288 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3289 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003290 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3291 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003292
hongzuo liu95785e22022-09-06 02:51:35 +00003293 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294
3295 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003299 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003300 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003301 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003302 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003303 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003304 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003305 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003306 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003307 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
3309 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003310 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 startDispatchCycleLocked(currentTime, connection);
3312 }
3313}
3314
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003315void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003317 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003318 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003319 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3320 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 return;
3322 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003323
3324 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3325 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
3327 // This is a new event.
3328 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003329 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003330 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003332 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3333 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003334 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003336 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003337 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003338 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3340 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003341 LOG(WARNING) << "channel " << connection->getInputChannelName()
3342 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 return; // skip the inconsistent event
3344 }
3345 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003348 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003349 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003350 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3351 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3352 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3353 static_cast<int32_t>(IdGenerator::Source::OTHER);
3354 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003355 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003357 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003359 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003361 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003363 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3365 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003366 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 }
3368 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003369 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3370 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003371 if (DEBUG_DISPATCH_CYCLE) {
3372 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3373 "enter event",
3374 connection->getInputChannelName().c_str());
3375 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003376 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3377 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003381 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3382 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3383 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003384 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3386 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003387 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003388 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003391 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3392 // devices being active at the same time in the same window, so if a new device is
3393 // active, cancel the gesture from the old device.
3394
3395 std::unique_ptr<EventEntry> cancelEvent =
3396 connection->inputState
3397 .cancelConflictingInputStream(motionEntry,
3398 dispatchEntry->resolvedAction);
3399 if (cancelEvent != nullptr) {
3400 LOG(INFO) << "Canceling pointers for device " << motionEntry.deviceId << " in "
3401 << connection->getInputChannelName() << " with event "
3402 << cancelEvent->getDescription();
3403 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3404 createDispatchEntry(inputTarget, std::move(cancelEvent),
3405 InputTarget::Flags::DISPATCH_AS_IS);
3406
3407 // Send these cancel events to the queue before sending the event from the new
3408 // device.
3409 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3410 }
3411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3413 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003414 LOG(WARNING) << "channel " << connection->getInputChannelName()
3415 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003416 return; // skip the inconsistent event
3417 }
3418
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003419 dispatchEntry->resolvedEventId =
3420 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3421 ? mIdGenerator.nextId()
3422 : motionEntry.id;
3423 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3424 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3425 ") to MotionEvent(id=0x%" PRIx32 ").",
3426 motionEntry.id, dispatchEntry->resolvedEventId);
3427 ATRACE_NAME(message.c_str());
3428 }
3429
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003430 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3431 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3432 // Skip reporting pointer down outside focus to the policy.
3433 break;
3434 }
3435
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003436 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003437 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438
3439 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003441 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003442 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003443 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3444 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003445 break;
3446 }
Chris Yef59a2f42020-10-16 12:55:26 -07003447 case EventEntry::Type::SENSOR: {
3448 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3449 break;
3450 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003451 case EventEntry::Type::CONFIGURATION_CHANGED:
3452 case EventEntry::Type::DEVICE_RESET: {
3453 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003454 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003455 break;
3456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 }
3458
3459 // Remember that we are waiting for this dispatch to complete.
3460 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003461 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 }
3463
3464 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003465 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003466 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003467}
3468
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003469/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003470 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003471 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003472 * The first role is to log input interaction with windows, which helps determine what the user was
3473 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3474 * that user started interacting with launcher window, as well as any other window that received
3475 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3476 * when the set of tokens that received the event changes. It is not logged again as long as the
3477 * user is interacting with the same windows.
3478 *
3479 * The second role is to track input device activity for metrics collection. For each input event,
3480 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3481 * input_interaction logs, the device interaction is reported even when the set of interaction
3482 * tokens do not change.
3483 *
3484 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3485 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003486 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003487void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3488 const std::vector<InputTarget>& targets) {
3489 int32_t deviceId;
3490 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003491 // Skip ACTION_UP events, and all events other than keys and motions
3492 if (entry.type == EventEntry::Type::KEY) {
3493 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3494 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3495 return;
3496 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003497 deviceId = keyEntry.deviceId;
3498 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003499 } else if (entry.type == EventEntry::Type::MOTION) {
3500 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3501 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003502 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3503 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003504 return;
3505 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003506 deviceId = motionEntry.deviceId;
3507 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003508 } else {
3509 return; // Not a key or a motion
3510 }
3511
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003512 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003513 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003514 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003515 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003516 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003517 continue; // Skip windows that receive ACTION_OUTSIDE
3518 }
3519
3520 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003521 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003522 if (connection == nullptr) {
3523 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003524 }
3525 newConnectionTokens.insert(std::move(token));
3526 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003527 if (target.windowHandle) {
3528 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3529 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003530 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003531
3532 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3533 REQUIRES(mLock) {
3534 scoped_unlock unlock(mLock);
3535 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3536 };
3537 postCommandLocked(std::move(command));
3538
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003539 if (newConnectionTokens == mInteractionConnectionTokens) {
3540 return; // no change
3541 }
3542 mInteractionConnectionTokens = newConnectionTokens;
3543
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003544 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003545 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003546 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003547 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003548 std::string message = "Interaction with: " + targetList;
3549 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003550 message += "<none>";
3551 }
3552 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3553}
3554
chaviwfd6d3512019-03-25 13:23:49 -07003555void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003556 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003557 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003558 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3559 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003560 return;
3561 }
3562
Vishnu Nairc519ff72021-01-21 08:23:08 -08003563 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003564 if (focusedToken == token) {
3565 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003566 return;
3567 }
3568
Prabir Pradhancef936d2021-07-21 16:17:52 +00003569 auto command = [this, token]() REQUIRES(mLock) {
3570 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003571 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003572 };
3573 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574}
3575
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003576status_t InputDispatcher::publishMotionEvent(Connection& connection,
3577 DispatchEntry& dispatchEntry) const {
3578 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3579 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3580
3581 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003582 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003583
3584 // Set the X and Y offset and X and Y scale depending on the input source.
3585 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003586 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003587 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3588 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003589 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003590 scaledCoords[i] = motionEntry.pointerCoords[i];
3591 // Don't apply window scale here since we don't want scale to affect raw
3592 // coordinates. The scale will be sent back to the client and applied
3593 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003594 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003595 }
3596 usingCoords = scaledCoords;
3597 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003598 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003599 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003600 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003601 scaledCoords[i].clear();
3602 }
3603 usingCoords = scaledCoords;
3604 }
3605
3606 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3607
3608 // Publish the motion event.
3609 return connection.inputPublisher
3610 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3611 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3612 std::move(hmac), dispatchEntry.resolvedAction,
3613 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3614 motionEntry.edgeFlags, motionEntry.metaState,
3615 motionEntry.buttonState, motionEntry.classification,
3616 dispatchEntry.transform, motionEntry.xPrecision,
3617 motionEntry.yPrecision, motionEntry.xCursorPosition,
3618 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3619 motionEntry.downTime, motionEntry.eventTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003620 motionEntry.getPointerCount(), motionEntry.pointerProperties.data(),
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003621 usingCoords);
3622}
3623
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003625 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003626 ATRACE_NAME_IF(ATRACE_ENABLED(),
3627 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3628 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003629 if (DEBUG_DISPATCH_CYCLE) {
3630 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003633 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003634 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003636 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003637 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638
3639 // Publish the event.
3640 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003641 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3642 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003643 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003644 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3645 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003646 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003647 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3648 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003651 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003652 status = connection->inputPublisher
3653 .publishKeyEvent(dispatchEntry->seq,
3654 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3655 keyEntry.source, keyEntry.displayId,
3656 std::move(hmac), dispatchEntry->resolvedAction,
3657 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3658 keyEntry.scanCode, keyEntry.metaState,
3659 keyEntry.repeatCount, keyEntry.downTime,
3660 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003664 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003665 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003666 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3667 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003668 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003669 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670 break;
3671 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003672
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003673 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003674 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003675 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003677 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003678 break;
3679 }
3680
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003681 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3682 const TouchModeEntry& touchModeEntry =
3683 static_cast<const TouchModeEntry&>(eventEntry);
3684 status = connection->inputPublisher
3685 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3686 touchModeEntry.inTouchMode);
3687
3688 break;
3689 }
3690
Prabir Pradhan99987712020-11-10 18:43:05 -08003691 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3692 const auto& captureEntry =
3693 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3694 status = connection->inputPublisher
3695 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003696 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003697 break;
3698 }
3699
arthurhungb89ccb02020-12-30 16:19:01 +08003700 case EventEntry::Type::DRAG: {
3701 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3702 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3703 dragEntry.id, dragEntry.x,
3704 dragEntry.y,
3705 dragEntry.isExiting);
3706 break;
3707 }
3708
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003709 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003710 case EventEntry::Type::DEVICE_RESET:
3711 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003712 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003713 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
3717
3718 // Check the result.
3719 if (status) {
3720 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003721 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 "This is unexpected because the wait queue is empty, so the pipe "
3724 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003725 "event to it, status=%s(%d)",
3726 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3727 status);
Harry Cutts33476232023-01-30 19:57:29 +00003728 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 } else {
3730 // Pipe is full and we are waiting for the app to finish process some events
3731 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003732 if (DEBUG_DISPATCH_CYCLE) {
3733 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3734 "waiting for the application to catch up",
3735 connection->getInputChannelName().c_str());
3736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 }
3738 } else {
3739 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003740 "status=%s(%d)",
3741 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3742 status);
Harry Cutts33476232023-01-30 19:57:29 +00003743 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745 return;
3746 }
3747
3748 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003749 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3750 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3751 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003752 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003753 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003754 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003755 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003756 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 }
3758}
3759
chaviw09c8d2d2020-08-24 15:48:26 -07003760std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3761 size_t size;
3762 switch (event.type) {
3763 case VerifiedInputEvent::Type::KEY: {
3764 size = sizeof(VerifiedKeyEvent);
3765 break;
3766 }
3767 case VerifiedInputEvent::Type::MOTION: {
3768 size = sizeof(VerifiedMotionEvent);
3769 break;
3770 }
3771 }
3772 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3773 return mHmacKeyManager.sign(start, size);
3774}
3775
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003776const std::array<uint8_t, 32> InputDispatcher::getSignature(
3777 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003778 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003779 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003780 // Only sign events up and down events as the purely move events
3781 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003782 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003783 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003784
3785 VerifiedMotionEvent verifiedEvent =
3786 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3787 verifiedEvent.actionMasked = actionMasked;
3788 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3789 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003790}
3791
3792const std::array<uint8_t, 32> InputDispatcher::getSignature(
3793 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3794 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3795 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3796 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003797 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003798}
3799
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003801 const std::shared_ptr<Connection>& connection,
3802 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003803 if (DEBUG_DISPATCH_CYCLE) {
3804 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3805 connection->getInputChannelName().c_str(), seq, toString(handled));
3806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003808 if (connection->status == Connection::Status::BROKEN ||
3809 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 return;
3811 }
3812
3813 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003814 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3815 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3816 };
3817 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818}
3819
3820void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003821 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003822 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003823 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003824 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3825 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827
3828 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003829 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003830 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003831 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003832 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833
3834 // The connection appears to be unrecoverably broken.
3835 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003836 if (connection->status == Connection::Status::NORMAL) {
3837 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
3839 if (notify) {
3840 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003841 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3842 connection->getInputChannelName().c_str());
3843
3844 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003845 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003846 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003847 };
3848 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 }
3850 }
3851}
3852
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003853void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003854 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003855 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003856 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 }
3858}
3859
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003860void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003862 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864}
3865
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003866int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3867 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003868 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003869 if (connection == nullptr) {
3870 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3871 connectionToken.get(), events);
3872 return 0; // remove the callback
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 bool notify;
3876 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3877 if (!(events & ALOOPER_EVENT_INPUT)) {
3878 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3879 "events=0x%x",
3880 connection->getInputChannelName().c_str(), events);
3881 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003884 nsecs_t currentTime = now();
3885 bool gotOne = false;
3886 status_t status = OK;
3887 for (;;) {
3888 Result<InputPublisher::ConsumerResponse> result =
3889 connection->inputPublisher.receiveConsumerResponse();
3890 if (!result.ok()) {
3891 status = result.error().code();
3892 break;
3893 }
3894
3895 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3896 const InputPublisher::Finished& finish =
3897 std::get<InputPublisher::Finished>(*result);
3898 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3899 finish.consumeTime);
3900 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003901 if (shouldReportMetricsForConnection(*connection)) {
3902 const InputPublisher::Timeline& timeline =
3903 std::get<InputPublisher::Timeline>(*result);
3904 mLatencyTracker
3905 .trackGraphicsLatency(timeline.inputEventId,
3906 connection->inputChannel->getConnectionToken(),
3907 std::move(timeline.graphicsTimeline));
3908 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003909 }
3910 gotOne = true;
3911 }
3912 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003913 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003914 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 return 1;
3916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003919 notify = status != DEAD_OBJECT || !connection->monitor;
3920 if (notify) {
3921 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3922 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3923 status);
3924 }
3925 } else {
3926 // Monitor channels are never explicitly unregistered.
3927 // We do it automatically when the remote endpoint is closed so don't warn about them.
3928 const bool stillHaveWindowHandle =
3929 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3930 notify = !connection->monitor && stillHaveWindowHandle;
3931 if (notify) {
3932 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3933 connection->getInputChannelName().c_str(), events);
3934 }
3935 }
3936
3937 // Remove the channel.
3938 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3939 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940}
3941
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003942void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003944 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003945 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 }
3947}
3948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003950 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003951 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003952 for (const Monitor& monitor : monitors) {
3953 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003954 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003955 }
3956}
3957
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003959 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003960 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003961 if (connection == nullptr) {
3962 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003964
3965 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966}
3967
3968void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003969 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li5af92f92023-07-14 14:36:22 +08003970 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3971 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3972 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3973 LOG(INFO) << __func__
3974 << ": Canceling drag and drop because the pointers for the drag window are being "
3975 "canceled.";
3976 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3977 mDragState.reset();
3978 }
3979
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003980 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 return;
3982 }
3983
3984 nsecs_t currentTime = now();
3985
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003986 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003987 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003989 if (cancelationEvents.empty()) {
3990 return;
3991 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003992 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3993 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003994 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003995 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003996 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003997 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003998
Arthur Hungb3307ee2021-10-14 10:57:37 +00003999 std::string reason = std::string("reason=").append(options.reason);
4000 android_log_event_list(LOGTAG_INPUT_CANCEL)
4001 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4002
hongzuo liu95785e22022-09-06 02:51:35 +00004003 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004004 // The target to use if we don't find a window associated with the channel.
4005 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
4006 .flags = InputTarget::Flags::DISPATCH_AS_IS};
4007 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004008
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004009 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004010 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004011 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004012
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004013 switch (cancelationEventEntry->type) {
4014 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004015 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004016 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4017 ? std::make_optional(keyEntry.displayId)
4018 : std::nullopt;
4019 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
4020 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004021 keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004022 } else {
4023 targets.emplace_back(fallbackTarget);
4024 }
4025 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004026 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004028 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004029 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004030 const std::optional<int32_t> targetDisplay =
4031 motionEntry.displayId != ADISPLAY_ID_NONE
4032 ? std::make_optional(motionEntry.displayId)
4033 : std::nullopt;
4034 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004035 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004036 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004037 pointerIndex++) {
4038 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4039 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004040 addPointerWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
4041 pointerIds, motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004042 } else {
4043 targets.emplace_back(fallbackTarget);
4044 const auto it = mDisplayInfos.find(motionEntry.displayId);
4045 if (it != mDisplayInfos.end()) {
4046 targets.back().displayTransform = it->second.transform;
4047 targets.back().setDefaultPointerTransform(it->second.transform);
4048 }
4049 }
4050 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004053 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004054 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004055 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4056 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004057 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004058 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004059 break;
4060 }
4061 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004062 case EventEntry::Type::DEVICE_RESET:
4063 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004064 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004065 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004066 break;
4067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 }
4069
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004070 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4071 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004072 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004074
hongzuo liu95785e22022-09-06 02:51:35 +00004075 // If the outbound queue was previously empty, start the dispatch cycle going.
4076 if (wasEmpty && !connection->outboundQueue.empty()) {
4077 startDispatchCycleLocked(currentTime, connection);
4078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079}
4080
Svet Ganov5d3bc372020-01-26 23:11:07 -08004081void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004082 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004083 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004084 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004085 return;
4086 }
4087
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004088 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004089 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004090
4091 if (downEvents.empty()) {
4092 return;
4093 }
4094
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004095 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004096 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4097 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004098 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004099
chaviw98318de2021-05-19 16:45:23 -05004100 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004101 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004102
hongzuo liu95785e22022-09-06 02:51:35 +00004103 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004104 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004105 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004106 switch (downEventEntry->type) {
4107 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004108 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4109 if (windowHandle != nullptr) {
4110 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004111 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004112 pointerIndex++) {
4113 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4114 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004115 addPointerWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4116 motionEntry.downTime, targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004117 } else {
4118 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4119 .flags = targetFlags});
4120 const auto it = mDisplayInfos.find(motionEntry.displayId);
4121 if (it != mDisplayInfos.end()) {
4122 targets.back().displayTransform = it->second.transform;
4123 targets.back().setDefaultPointerTransform(it->second.transform);
4124 }
4125 }
4126 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004127 break;
4128 }
4129
4130 case EventEntry::Type::KEY:
4131 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004132 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004133 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004134 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004135 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004136 case EventEntry::Type::SENSOR:
4137 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004138 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004139 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004140 break;
4141 }
4142 }
4143
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004144 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4145 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004146 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004147 }
4148
hongzuo liu95785e22022-09-06 02:51:35 +00004149 // If the outbound queue was previously empty, start the dispatch cycle going.
4150 if (wasEmpty && !connection->outboundQueue.empty()) {
4151 startDispatchCycleLocked(downTime, connection);
4152 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004153}
4154
Arthur Hungc539dbb2022-12-08 07:45:36 +00004155void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4156 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4157 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004158 std::shared_ptr<Connection> wallpaperConnection =
4159 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004160 if (wallpaperConnection != nullptr) {
4161 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4162 }
4163 }
4164}
4165
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004166std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004167 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4168 nsecs_t splitDownTime) {
4169 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170
4171 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004172 std::vector<PointerProperties> splitPointerProperties;
4173 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004175 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 uint32_t splitPointerCount = 0;
4177
4178 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004179 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004181 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004183 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004185 splitPointerProperties.push_back(pointerProperties);
4186 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 splitPointerCount += 1;
4188 }
4189 }
4190
4191 if (splitPointerCount != pointerIds.count()) {
4192 // This is bad. We are missing some of the pointers that we expected to deliver.
4193 // Most likely this indicates that we received an ACTION_MOVE events that has
4194 // different pointer ids than we expected based on the previous ACTION_DOWN
4195 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4196 // in this way.
4197 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004198 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004199 "a broken sequence of pointer ids from the input device: %s",
4200 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004201 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
4203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004204 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4207 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004208 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004210 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004212 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 if (pointerIds.count() == 1) {
4214 // The first/last pointer went down/up.
4215 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004217 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4218 ? AMOTION_EVENT_ACTION_CANCEL
4219 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 } else {
4221 // A secondary pointer went down/up.
4222 uint32_t splitPointerIndex = 0;
4223 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4224 splitPointerIndex += 1;
4225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 action = maskedAction |
4227 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 }
4229 } else {
4230 // An unrelated pointer changed.
4231 action = AMOTION_EVENT_ACTION_MOVE;
4232 }
4233 }
4234
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004235 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4236 logDispatchStateLocked();
4237 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4238 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4239 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004240 }
4241
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004242 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004243 ATRACE_NAME_IF(ATRACE_ENABLED(),
4244 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4245 ").",
4246 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 std::unique_ptr<MotionEntry> splitMotionEntry =
4248 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4249 originalMotionEntry.deviceId, originalMotionEntry.source,
4250 originalMotionEntry.displayId,
4251 originalMotionEntry.policyFlags, action,
4252 originalMotionEntry.actionButton,
4253 originalMotionEntry.flags, originalMotionEntry.metaState,
4254 originalMotionEntry.buttonState,
4255 originalMotionEntry.classification,
4256 originalMotionEntry.edgeFlags,
4257 originalMotionEntry.xPrecision,
4258 originalMotionEntry.yPrecision,
4259 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004260 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004261 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004263 if (originalMotionEntry.injectionState) {
4264 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 splitMotionEntry->injectionState->refCount += 1;
4266 }
4267
4268 return splitMotionEntry;
4269}
4270
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004271void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4272 std::scoped_lock _l(mLock);
4273 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4274}
4275
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004276void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004277 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004278 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Antonio Kantekf16f2832021-09-28 04:39:20 +00004281 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004285 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004286 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 } // release lock
4289
4290 if (needWake) {
4291 mLooper->wake();
4292 }
4293}
4294
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004295void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004296 ALOGD_IF(debugInboundEventDetails(),
4297 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4298 ", deviceId=%d, source=%s, displayId=%" PRId32
4299 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4300 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004301 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4302 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4303 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004304 Result<void> keyCheck = validateKeyEvent(args.action);
4305 if (!keyCheck.ok()) {
4306 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 return;
4308 }
4309
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004310 uint32_t policyFlags = args.policyFlags;
4311 int32_t flags = args.flags;
4312 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004313 // InputDispatcher tracks and generates key repeats on behalf of
4314 // whatever notifies it, so repeatCount should always be set to 0
4315 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4317 policyFlags |= POLICY_FLAG_VIRTUAL;
4318 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 if (policyFlags & POLICY_FLAG_FUNCTION) {
4321 metaState |= AMETA_FUNCTION_ON;
4322 }
4323
4324 policyFlags |= POLICY_FLAG_TRUSTED;
4325
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004326 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004328 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4329 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4330 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331
Michael Wright2b3c3302018-03-02 17:19:13 +00004332 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004333 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004334 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4335 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
Antonio Kantekf16f2832021-09-28 04:39:20 +00004339 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 { // acquire lock
4341 mLock.lock();
4342
4343 if (shouldSendKeyToInputFilterLocked(args)) {
4344 mLock.unlock();
4345
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004346 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004347 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 return; // event was consumed by the filter
4349 }
4350
4351 mLock.lock();
4352 }
4353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004354 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004355 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4356 args.displayId, policyFlags, args.action, flags, keyCode,
4357 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 mLock.unlock();
4361 } // release lock
4362
4363 if (needWake) {
4364 mLooper->wake();
4365 }
4366}
4367
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004368bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 return mInputFilterEnabled;
4370}
4371
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004372void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004373 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004374 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004375 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004376 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004377 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4378 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4380 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4381 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4382 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4383 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004384 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004385 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4386 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004387 i, args.pointerProperties[i].id,
4388 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4389 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4390 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4391 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4392 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4393 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4394 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4395 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4396 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4397 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004400
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004401 Result<void> motionCheck =
4402 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4403 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004404 if (!motionCheck.ok()) {
4405 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4406 return;
4407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004409 if (DEBUG_VERIFY_EVENTS) {
4410 auto [it, _] =
4411 mVerifiersByDisplay.try_emplace(args.displayId,
4412 StringPrintf("display %" PRId32, args.displayId));
4413 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004414 it->second.processMovement(args.deviceId, args.source, args.action,
4415 args.getPointerCount(), args.pointerProperties.data(),
4416 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004417 if (!result.ok()) {
4418 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4419 }
4420 }
4421
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004422 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004424
4425 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004426 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004427 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4428 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Antonio Kantekf16f2832021-09-28 04:39:20 +00004432 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 { // acquire lock
4434 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004435 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4436 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4437 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004438 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004439 if (touchStateIt != mTouchStatesByDisplay.end()) {
4440 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004441 if (touchState.hasTouchingPointers(args.deviceId) ||
4442 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004443 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4444 }
4445 }
4446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447
4448 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004449 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004450 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004451 displayTransform = it->second.transform;
4452 }
4453
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 mLock.unlock();
4455
4456 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004457 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4458 args.action, args.actionButton, args.flags, args.edgeFlags,
4459 args.metaState, args.buttonState, args.classification,
4460 displayTransform, args.xPrecision, args.yPrecision,
4461 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004462 args.downTime, args.eventTime, args.getPointerCount(),
4463 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
4465 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004466 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 return; // event was consumed by the filter
4468 }
4469
4470 mLock.lock();
4471 }
4472
4473 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004474 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004475 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4476 args.displayId, policyFlags, args.action,
4477 args.actionButton, args.flags, args.metaState,
4478 args.buttonState, args.classification, args.edgeFlags,
4479 args.xPrecision, args.yPrecision,
4480 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004481 args.downTime, args.pointerProperties,
4482 args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004484 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4485 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004486 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004488 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4489 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4490 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004491 }
4492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 mLock.unlock();
4495 } // release lock
4496
4497 if (needWake) {
4498 mLooper->wake();
4499 }
4500}
4501
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004502void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004503 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004504 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4505 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004506 args.id, args.eventTime, args.deviceId, args.source,
4507 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004508 }
Chris Yef59a2f42020-10-16 12:55:26 -07004509
Antonio Kantekf16f2832021-09-28 04:39:20 +00004510 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004511 { // acquire lock
4512 mLock.lock();
4513
4514 // Just enqueue a new sensor event.
4515 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004516 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4517 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4518 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004519
4520 needWake = enqueueInboundEventLocked(std::move(newEntry));
4521 mLock.unlock();
4522 } // release lock
4523
4524 if (needWake) {
4525 mLooper->wake();
4526 }
4527}
4528
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004529void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004530 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004531 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4532 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004533 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004534 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004535}
4536
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004537bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004538 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539}
4540
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004541void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004542 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004543 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4544 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004545 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004548 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004550 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551}
4552
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004553void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Siarhei Vishniakou96e4fad2023-09-20 09:30:44 -07004554 // TODO(b/308677868) Remove device reset from the InputListener interface
Prabir Pradhan65613802023-02-22 23:36:58 +00004555 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004556 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4557 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Antonio Kantekf16f2832021-09-28 04:39:20 +00004560 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004562 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004564 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004565 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004566 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004567
4568 for (auto& [_, verifier] : mVerifiersByDisplay) {
4569 verifier.resetDevice(args.deviceId);
4570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 } // release lock
4572
4573 if (needWake) {
4574 mLooper->wake();
4575 }
4576}
4577
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004578void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004579 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004580 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4581 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004582 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004583
Antonio Kantekf16f2832021-09-28 04:39:20 +00004584 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004585 { // acquire lock
4586 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004587 auto entry =
4588 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004589 needWake = enqueueInboundEventLocked(std::move(entry));
4590 } // release lock
4591
4592 if (needWake) {
4593 mLooper->wake();
4594 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004595}
4596
Prabir Pradhan5735a322022-04-11 17:23:34 +00004597InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004598 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004599 InputEventInjectionSync syncMode,
4600 std::chrono::milliseconds timeout,
4601 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004602 Result<void> eventValidation = validateInputEvent(*event);
4603 if (!eventValidation.ok()) {
4604 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4605 return InputEventInjectionResult::FAILED;
4606 }
4607
Prabir Pradhan65613802023-02-22 23:36:58 +00004608 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004609 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4610 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4611 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4612 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004613 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004614 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615
Prabir Pradhan5735a322022-04-11 17:23:34 +00004616 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004618 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004619 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4620 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4621 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4622 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4623 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004624 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004625 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004626 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004627 }
4628
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004629 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004631 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004632 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004633 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004634 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004635 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4636 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4637 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004638 int32_t keyCode = incomingKey.getKeyCode();
4639 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004640 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004641 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004642 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4643 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4644 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004646 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4647 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004648 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004649
4650 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4651 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004652 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004653 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4654 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4655 std::to_string(t.duration().count()).c_str());
4656 }
4657 }
4658
4659 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004660 std::unique_ptr<KeyEntry> injectedEntry =
4661 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004662 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004663 incomingKey.getDisplayId(), policyFlags, action,
4664 flags, keyCode, incomingKey.getScanCode(), metaState,
4665 incomingKey.getRepeatCount(),
4666 incomingKey.getDownTime());
4667 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004668 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 }
4670
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004671 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004672 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004673 const bool isPointerEvent =
4674 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4675 // If a pointer event has no displayId specified, inject it to the default display.
4676 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4677 ? ADISPLAY_ID_DEFAULT
4678 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004679 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680
4681 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004682 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004683 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004684 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4686 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4687 std::to_string(t.duration().count()).c_str());
4688 }
4689 }
4690
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004691 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4692 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4693 }
4694
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004695 mLock.lock();
Siarhei Vishniakou96e4fad2023-09-20 09:30:44 -07004696
4697 if (policyFlags & POLICY_FLAG_FILTERED) {
4698 // The events from InputFilter impersonate real hardware devices. Check these
4699 // events for consistency and print an error. An inconsistent event sent from
4700 // InputFilter could cause a crash in the later stages of dispatching pipeline.
4701 auto [it, _] =
4702 mInputFilterVerifiersByDisplay
4703 .try_emplace(displayId,
4704 StringPrintf("Injection on %" PRId32, displayId));
4705 InputVerifier& verifier = it->second;
4706
4707 Result<void> result =
4708 verifier.processMovement(resolvedDeviceId, motionEvent.getSource(),
4709 motionEvent.getAction(),
4710 motionEvent.getPointerCount(),
4711 motionEvent.getPointerProperties(),
4712 motionEvent.getSamplePointerCoords(), flags);
4713 if (!result.ok()) {
4714 logDispatchStateLocked();
4715 LOG(ERROR) << "Inconsistent event: " << motionEvent
4716 << ", reason: " << result.error();
4717 }
4718 }
4719
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004720 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004721 const size_t pointerCount = motionEvent.getPointerCount();
4722 const std::vector<PointerProperties>
4723 pointerProperties(motionEvent.getPointerProperties(),
4724 motionEvent.getPointerProperties() + pointerCount);
4725
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004726 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004727 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004728 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4729 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004730 displayId, policyFlags, motionEvent.getAction(),
4731 motionEvent.getActionButton(), flags,
4732 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004733 motionEvent.getButtonState(),
4734 motionEvent.getClassification(),
4735 motionEvent.getEdgeFlags(),
4736 motionEvent.getXPrecision(),
4737 motionEvent.getYPrecision(),
4738 motionEvent.getRawXCursorPosition(),
4739 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004740 motionEvent.getDownTime(), pointerProperties,
4741 std::vector<PointerCoords>(samplePointerCoords,
4742 samplePointerCoords +
4743 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004744 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004745 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004746 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004747 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004748 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004749 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
4750 MotionEntry>(motionEvent.getId(), *sampleEventTimes, resolvedDeviceId,
4751 motionEvent.getSource(), displayId, policyFlags,
4752 motionEvent.getAction(), motionEvent.getActionButton(), flags,
4753 motionEvent.getMetaState(), motionEvent.getButtonState(),
4754 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4755 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4756 motionEvent.getRawXCursorPosition(),
4757 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4758 pointerProperties,
4759 std::vector<PointerCoords>(samplePointerCoords,
4760 samplePointerCoords +
4761 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004762 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4763 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004764 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004765 }
4766 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004770 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004771 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773
Prabir Pradhan5735a322022-04-11 17:23:34 +00004774 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004775 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 injectionState->injectionIsAsync = true;
4777 }
4778
4779 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004780 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781
4782 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004783 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004784 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004785 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004786 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004787 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004788 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 }
4790
4791 mLock.unlock();
4792
4793 if (needWake) {
4794 mLooper->wake();
4795 }
4796
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004797 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004799 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004801 if (syncMode == InputEventInjectionSync::NONE) {
4802 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 } else {
4804 for (;;) {
4805 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004806 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 break;
4808 }
4809
4810 nsecs_t remainingTimeout = endTime - now();
4811 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004812 if (DEBUG_INJECTION) {
4813 ALOGD("injectInputEvent - Timed out waiting for injection result "
4814 "to become available.");
4815 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 break;
4818 }
4819
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004820 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 }
4822
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4824 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004826 if (DEBUG_INJECTION) {
4827 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4828 injectionState->pendingForegroundDispatches);
4829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 nsecs_t remainingTimeout = endTime - now();
4831 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004832 if (DEBUG_INJECTION) {
4833 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4834 "dispatches to finish.");
4835 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 break;
4838 }
4839
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004840 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 }
4842 }
4843 }
4844
4845 injectionState->release();
4846 } // release lock
4847
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004848 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004849 LOG(INFO) << "injectInputEvent - Finished with result "
4850 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852
4853 return injectionResult;
4854}
4855
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004856std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004857 std::array<uint8_t, 32> calculatedHmac;
4858 std::unique_ptr<VerifiedInputEvent> result;
4859 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004860 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004861 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4862 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4863 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004864 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004865 break;
4866 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004867 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004868 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4869 VerifiedMotionEvent verifiedMotionEvent =
4870 verifiedMotionEventFromMotionEvent(motionEvent);
4871 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004872 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004873 break;
4874 }
4875 default: {
4876 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4877 return nullptr;
4878 }
4879 }
4880 if (calculatedHmac == INVALID_HMAC) {
4881 return nullptr;
4882 }
tyiu1573a672023-02-21 22:38:32 +00004883 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004884 return nullptr;
4885 }
4886 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004887}
4888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004889void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004890 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004891 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004893 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004894 LOG(INFO) << "Setting input event injection result to "
4895 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004898 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 // Log the outcome since the injector did not wait for the injection result.
4900 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004902 ALOGV("Asynchronous input event injection succeeded.");
4903 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004904 case InputEventInjectionResult::TARGET_MISMATCH:
4905 ALOGV("Asynchronous input event injection target mismatch.");
4906 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004907 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004908 ALOGW("Asynchronous input event injection failed.");
4909 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004910 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004911 ALOGW("Asynchronous input event injection timed out.");
4912 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004913 case InputEventInjectionResult::PENDING:
4914 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4915 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 }
4917 }
4918
4919 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004920 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 }
4922}
4923
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004924void InputDispatcher::transformMotionEntryForInjectionLocked(
4925 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004926 // Input injection works in the logical display coordinate space, but the input pipeline works
4927 // display space, so we need to transform the injected events accordingly.
4928 const auto it = mDisplayInfos.find(entry.displayId);
4929 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004930 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004931
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004932 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4933 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4934 const vec2 cursor =
4935 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4936 {entry.xCursorPosition, entry.yCursorPosition});
4937 entry.xCursorPosition = cursor.x;
4938 entry.yCursorPosition = cursor.y;
4939 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004940 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004941 entry.pointerCoords[i] =
4942 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4943 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004944 }
4945}
4946
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004947void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4948 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 if (injectionState) {
4950 injectionState->pendingForegroundDispatches += 1;
4951 }
4952}
4953
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004954void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4955 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 if (injectionState) {
4957 injectionState->pendingForegroundDispatches -= 1;
4958
4959 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004960 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961 }
4962 }
4963}
4964
chaviw98318de2021-05-19 16:45:23 -05004965const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004966 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004967 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004968 auto it = mWindowHandlesByDisplay.find(displayId);
4969 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004970}
4971
chaviw98318de2021-05-19 16:45:23 -05004972sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004973 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004974 if (windowHandleToken == nullptr) {
4975 return nullptr;
4976 }
4977
Prabir Pradhan16463382023-10-12 23:03:19 +00004978 if (!displayId) {
4979 // Look through all displays.
4980 for (auto& it : mWindowHandlesByDisplay) {
4981 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4982 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4983 if (windowHandle->getToken() == windowHandleToken) {
4984 return windowHandle;
4985 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004988 return nullptr;
4989 }
4990
Prabir Pradhan16463382023-10-12 23:03:19 +00004991 // Only look through the requested display.
4992 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004993 if (windowHandle->getToken() == windowHandleToken) {
4994 return windowHandle;
4995 }
4996 }
4997 return nullptr;
4998}
4999
chaviw98318de2021-05-19 16:45:23 -05005000sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5001 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005002 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005003 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5004 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005005 if (handle->getId() == windowHandle->getId() &&
5006 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005007 if (windowHandle->getInfo()->displayId != it.first) {
5008 ALOGE("Found window %s in display %" PRId32
5009 ", but it should belong to display %" PRId32,
5010 windowHandle->getName().c_str(), it.first,
5011 windowHandle->getInfo()->displayId);
5012 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005013 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 }
5016 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005017 return nullptr;
5018}
5019
chaviw98318de2021-05-19 16:45:23 -05005020sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005021 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5022 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023}
5024
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005025ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5026 auto displayInfoIt = mDisplayInfos.find(displayId);
5027 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5028 : kIdentityTransform;
5029}
5030
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005031bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5032 const MotionEntry& motionEntry) const {
5033 const WindowInfo& info = *window->getInfo();
5034
5035 // Skip spy window targets that are not valid for targeted injection.
5036 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005037 return false;
5038 }
5039
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005040 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5041 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5042 return false;
5043 }
5044
5045 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5046 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5047 window->getName().c_str());
5048 return false;
5049 }
5050
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005051 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005052 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005053 ALOGW("Not sending touch to %s because there's no corresponding connection",
5054 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005055 return false;
5056 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005057
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005058 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005059 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005060 return false;
5061 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005062
5063 // Drop events that can't be trusted due to occlusion
5064 const auto [x, y] = resolveTouchedPosition(motionEntry);
5065 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5066 if (!isTouchTrustedLocked(occlusionInfo)) {
5067 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005068 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005069 for (const auto& log : occlusionInfo.debugInfo) {
5070 ALOGD("%s", log.c_str());
5071 }
5072 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005073 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5074 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005075 return false;
5076 }
5077
5078 // Drop touch events if requested by input feature
5079 if (shouldDropInput(motionEntry, window)) {
5080 return false;
5081 }
5082
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005083 return true;
5084}
5085
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005086std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5087 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005088 auto connectionIt = mConnectionsByToken.find(token);
5089 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005090 return nullptr;
5091 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005092 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005093}
5094
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005095void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005096 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5097 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005098 // Remove all handles on a display if there are no windows left.
5099 mWindowHandlesByDisplay.erase(displayId);
5100 return;
5101 }
5102
5103 // Since we compare the pointer of input window handles across window updates, we need
5104 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005105 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5106 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5107 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005108 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005109 }
5110
chaviw98318de2021-05-19 16:45:23 -05005111 std::vector<sp<WindowInfoHandle>> newHandles;
5112 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005113 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005114 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005115 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005116 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005117 const bool canReceiveInput =
5118 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5119 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005120 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005121 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005122 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005123 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005124 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005125 }
5126
5127 if (info->displayId != displayId) {
5128 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5129 handle->getName().c_str(), displayId, info->displayId);
5130 continue;
5131 }
5132
Robert Carredd13602020-04-13 17:24:34 -07005133 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5134 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005135 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005136 oldHandle->updateFrom(handle);
5137 newHandles.push_back(oldHandle);
5138 } else {
5139 newHandles.push_back(handle);
5140 }
5141 }
5142
5143 // Insert or replace
5144 mWindowHandlesByDisplay[displayId] = newHandles;
5145}
5146
Arthur Hungb92218b2018-08-14 12:00:21 +08005147/**
5148 * Called from InputManagerService, update window handle list by displayId that can receive input.
5149 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5150 * If set an empty list, remove all handles from the specific display.
5151 * For focused handle, check if need to change and send a cancel event to previous one.
5152 * For removed handle, check if need to send a cancel event if already in touch.
5153 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005154void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005155 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005156 if (DEBUG_FOCUS) {
5157 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005158 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005159 windowList += iwh->getName() + " ";
5160 }
5161 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163
Prabir Pradhand65552b2021-10-07 11:23:50 -07005164 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005165 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005166 const WindowInfo& info = *window->getInfo();
5167
5168 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005169 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005170 if (noInputWindow && window->getToken() != nullptr) {
5171 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5172 window->getName().c_str());
5173 window->releaseChannel();
5174 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005175
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005176 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005177 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5178 !info.inputConfig.test(
5179 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005180 "%s has feature SPY, but is not a trusted overlay.",
5181 window->getName().c_str());
5182
Prabir Pradhand65552b2021-10-07 11:23:50 -07005183 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005184 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5185 !info.inputConfig.test(
5186 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005187 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5188 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005189 }
5190
Arthur Hung72d8dc32020-03-28 00:48:39 +00005191 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005192 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193
chaviw98318de2021-05-19 16:45:23 -05005194 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005195
chaviw98318de2021-05-19 16:45:23 -05005196 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005197
Vishnu Nairc519ff72021-01-21 08:23:08 -08005198 std::optional<FocusResolver::FocusChanges> changes =
5199 mFocusResolver.setInputWindows(displayId, windowHandles);
5200 if (changes) {
5201 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005204 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5205 mTouchStatesByDisplay.find(displayId);
5206 if (stateIt != mTouchStatesByDisplay.end()) {
5207 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005208 for (size_t i = 0; i < state.windows.size();) {
5209 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005210 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005211 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5212 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005213 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005214 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5215 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005216 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005217 "touched window was removed");
5218 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005219 // Since we are about to drop the touch, cancel the events for the wallpaper as
5220 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005221 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005222 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5223 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005224 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005225 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005228 state.windows.erase(state.windows.begin() + i);
5229 } else {
5230 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 }
5232 }
arthurhungb89ccb02020-12-30 16:19:01 +08005233
arthurhung6d4bed92021-03-17 11:59:33 +08005234 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005235 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005236 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005237 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005238 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005239 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5240 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005241 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005242 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005243 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005244
Arthur Hung72d8dc32020-03-28 00:48:39 +00005245 // Release information for windows that are no longer present.
5246 // This ensures that unused input channels are released promptly.
5247 // Otherwise, they might stick around until the window handle is destroyed
5248 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005249 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005250 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005251 if (DEBUG_FOCUS) {
5252 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005253 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005254 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005255 }
chaviw291d88a2019-02-14 10:33:58 -08005256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257}
5258
5259void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005260 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005261 if (DEBUG_FOCUS) {
5262 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5263 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5264 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005265 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005266 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005267 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 } // release lock
5269
5270 // Wake up poll loop since it may need to make new input dispatching choices.
5271 mLooper->wake();
5272}
5273
Vishnu Nair599f1412021-06-21 10:39:58 -07005274void InputDispatcher::setFocusedApplicationLocked(
5275 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5276 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5277 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5278
5279 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5280 return; // This application is already focused. No need to wake up or change anything.
5281 }
5282
5283 // Set the new application handle.
5284 if (inputApplicationHandle != nullptr) {
5285 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5286 } else {
5287 mFocusedApplicationHandlesByDisplay.erase(displayId);
5288 }
5289
5290 // No matter what the old focused application was, stop waiting on it because it is
5291 // no longer focused.
5292 resetNoFocusedWindowTimeoutLocked();
5293}
5294
Tiger Huang721e26f2018-07-24 22:26:19 +08005295/**
5296 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5297 * the display not specified.
5298 *
5299 * We track any unreleased events for each window. If a window loses the ability to receive the
5300 * released event, we will send a cancel event to it. So when the focused display is changed, we
5301 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5302 * display. The display-specified events won't be affected.
5303 */
5304void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005305 if (DEBUG_FOCUS) {
5306 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5307 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005308 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005309 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005310
5311 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005312 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005313 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005314 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005315 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005316 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005317 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005318 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005319 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005320 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005321 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005322 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5323 }
5324 }
5325 mFocusedDisplayId = displayId;
5326
Chris Ye3c2d6f52020-08-09 10:39:48 -07005327 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005328 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005329 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005330
Vishnu Nairad321cd2020-08-20 16:40:21 -07005331 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005332 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005333 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005334 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005335 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005336 }
5337 }
5338 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005339 } // release lock
5340
5341 // Wake up poll loop since it may need to make new input dispatching choices.
5342 mLooper->wake();
5343}
5344
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005346 if (DEBUG_FOCUS) {
5347 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349
5350 bool changed;
5351 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005352 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353
5354 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5355 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005356 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 }
5358
5359 if (mDispatchEnabled && !enabled) {
5360 resetAndDropEverythingLocked("dispatcher is being disabled");
5361 }
5362
5363 mDispatchEnabled = enabled;
5364 mDispatchFrozen = frozen;
5365 changed = true;
5366 } else {
5367 changed = false;
5368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 } // release lock
5370
5371 if (changed) {
5372 // Wake up poll loop since it may need to make new input dispatching choices.
5373 mLooper->wake();
5374 }
5375}
5376
5377void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005378 if (DEBUG_FOCUS) {
5379 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381
5382 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005383 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384
5385 if (mInputFilterEnabled == enabled) {
5386 return;
5387 }
5388
5389 mInputFilterEnabled = enabled;
5390 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5391 } // release lock
5392
5393 // Wake up poll loop since there might be work to do to drop everything.
5394 mLooper->wake();
5395}
5396
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005397bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005398 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005399 bool needWake = false;
5400 {
5401 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005402 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005403 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005404 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005405 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5406 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005407 mTouchModePerDisplay.count(displayId) == 0
5408 ? "not set"
5409 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5410
Antonio Kantek15beb512022-06-13 22:35:41 +00005411 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5412 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005413 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005414 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005415 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005416 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5417 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005418 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005419 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005420 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005421 return false;
5422 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005423 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005424 mTouchModePerDisplay[displayId] = inTouchMode;
5425 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5426 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005427 needWake = enqueueInboundEventLocked(std::move(entry));
5428 } // release lock
5429
5430 if (needWake) {
5431 mLooper->wake();
5432 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005433 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005434}
5435
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005436bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005437 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5438 if (focusedToken == nullptr) {
5439 return false;
5440 }
5441 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5442 return isWindowOwnedBy(windowHandle, pid, uid);
5443}
5444
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005445bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005446 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5447 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5448 const sp<WindowInfoHandle> windowHandle =
5449 getWindowHandleLocked(connectionToken);
5450 return isWindowOwnedBy(windowHandle, pid, uid);
5451 }) != mInteractionConnectionTokens.end();
5452}
5453
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005454void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5455 if (opacity < 0 || opacity > 1) {
5456 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5457 return;
5458 }
5459
5460 std::scoped_lock lock(mLock);
5461 mMaximumObscuringOpacityForTouch = opacity;
5462}
5463
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005464std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5465InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005466 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5467 for (TouchedWindow& w : state.windows) {
5468 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005469 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005470 }
5471 }
5472 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005473 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005474}
5475
arthurhungb89ccb02020-12-30 16:19:01 +08005476bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5477 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005478 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005479 if (DEBUG_FOCUS) {
5480 ALOGD("Trivial transfer to same window.");
5481 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005482 return true;
5483 }
5484
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005486 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487
Arthur Hungabbb9d82021-09-01 14:52:30 +00005488 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005489 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005490
Arthur Hungabbb9d82021-09-01 14:52:30 +00005491 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005492 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 return false;
5494 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005495 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5496 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005497 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5498 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005499 return false;
5500 }
5501 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005502
Arthur Hungabbb9d82021-09-01 14:52:30 +00005503 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5504 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005505 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005506 return false;
5507 }
5508
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005509 if (DEBUG_FOCUS) {
5510 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005511 touchedWindow->windowHandle->getName().c_str(),
5512 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 }
5514
Arthur Hungabbb9d82021-09-01 14:52:30 +00005515 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005516 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005517 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005518 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005519 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520
Arthur Hungabbb9d82021-09-01 14:52:30 +00005521 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005522 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005523 ftl::Flags<InputTarget::Flags> newTargetFlags =
5524 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005525 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005526 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005527 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005528 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5529 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530
Arthur Hungabbb9d82021-09-01 14:52:30 +00005531 // Store the dragging window.
5532 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005533 if (pointerIds.count() != 1) {
5534 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5535 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005536 return false;
5537 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005538 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005539 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005540 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 }
5542
Arthur Hungabbb9d82021-09-01 14:52:30 +00005543 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005544 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5545 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005546 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005547 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005548 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5549 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005551 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5552 newTargetFlags);
5553
5554 // Check if the wallpaper window should deliver the corresponding event.
5555 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005556 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 } // release lock
5559
5560 // Wake up poll loop since it may need to make new input dispatching choices.
5561 mLooper->wake();
5562 return true;
5563}
5564
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005565/**
5566 * Get the touched foreground window on the given display.
5567 * Return null if there are no windows touched on that display, or if more than one foreground
5568 * window is being touched.
5569 */
5570sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5571 auto stateIt = mTouchStatesByDisplay.find(displayId);
5572 if (stateIt == mTouchStatesByDisplay.end()) {
5573 ALOGI("No touch state on display %" PRId32, displayId);
5574 return nullptr;
5575 }
5576
5577 const TouchState& state = stateIt->second;
5578 sp<WindowInfoHandle> touchedForegroundWindow;
5579 // If multiple foreground windows are touched, return nullptr
5580 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005581 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005582 if (touchedForegroundWindow != nullptr) {
5583 ALOGI("Two or more foreground windows: %s and %s",
5584 touchedForegroundWindow->getName().c_str(),
5585 window.windowHandle->getName().c_str());
5586 return nullptr;
5587 }
5588 touchedForegroundWindow = window.windowHandle;
5589 }
5590 }
5591 return touchedForegroundWindow;
5592}
5593
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005594// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005595bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005596 sp<IBinder> fromToken;
5597 { // acquire lock
5598 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005599 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005600 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005601 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5602 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005603 return false;
5604 }
5605
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005606 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5607 if (from == nullptr) {
5608 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5609 return false;
5610 }
5611
5612 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005613 } // release lock
5614
5615 return transferTouchFocus(fromToken, destChannelToken);
5616}
5617
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005619 if (DEBUG_FOCUS) {
5620 ALOGD("Resetting and dropping all events (%s).", reason);
5621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622
Michael Wrightfb04fd52022-11-24 22:31:11 +00005623 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 synthesizeCancelationEventsForAllConnectionsLocked(options);
5625
5626 resetKeyRepeatLocked();
5627 releasePendingEventLocked();
5628 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005629 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005631 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005632 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633}
5634
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005635void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005636 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 dumpDispatchStateLocked(dump);
5638
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005639 std::istringstream stream(dump);
5640 std::string line;
5641
5642 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005643 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 }
5645}
5646
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005647std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005648 std::string dump;
5649
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005650 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5651 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005652
5653 std::string windowName = "None";
5654 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005655 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005656 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5657 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5658 : "token has capture without window";
5659 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005660 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005661
5662 return dump;
5663}
5664
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005665void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005666 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5667 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5668 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005669 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670
Tiger Huang721e26f2018-07-24 22:26:19 +08005671 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5672 dump += StringPrintf(INDENT "FocusedApplications:\n");
5673 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5674 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005675 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005676 const std::chrono::duration timeout =
5677 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005678 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005679 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005680 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005683 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005685
Vishnu Nairc519ff72021-01-21 08:23:08 -08005686 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005687 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005689 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005690 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005691 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005692 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5693 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694 }
5695 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005696 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697 }
5698
arthurhung6d4bed92021-03-17 11:59:33 +08005699 if (mDragState) {
5700 dump += StringPrintf(INDENT "DragState:\n");
5701 mDragState->dump(dump, INDENT2);
5702 }
5703
Arthur Hungb92218b2018-08-14 12:00:21 +08005704 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005705 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5706 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5707 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5708 const auto& displayInfo = it->second;
5709 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5710 displayInfo.logicalHeight);
5711 displayInfo.transform.dump(dump, "transform", INDENT4);
5712 } else {
5713 dump += INDENT2 "No DisplayInfo found!\n";
5714 }
5715
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005716 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005717 dump += INDENT2 "Windows:\n";
5718 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005719 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5720 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005722 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005723 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005724 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005725 "applicationInfo.name=%s, "
5726 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005727 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005728 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005729 windowInfo->displayId,
5730 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005731 windowInfo->alpha, windowInfo->frame.left,
5732 windowInfo->frame.top, windowInfo->frame.right,
5733 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005734 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005735 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005736 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005737 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005738 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005739 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005740 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005741 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005742 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005743 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005744 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005745 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005746 }
5747 } else {
5748 dump += INDENT2 "Windows: <none>\n";
5749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750 }
5751 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005752 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 }
5754
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005755 if (!mGlobalMonitorsByDisplay.empty()) {
5756 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5757 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005758 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005761 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005764 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765
5766 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005767 if (!mRecentQueue.empty()) {
5768 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005769 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005770 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005771 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005772 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 }
5774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 }
5777
5778 // Dump event currently being dispatched.
5779 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005780 dump += INDENT "PendingEvent:\n";
5781 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005782 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005783 dump += StringPrintf(", age=%" PRId64 "ms\n",
5784 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 }
5788
5789 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005790 if (!mInboundQueue.empty()) {
5791 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005792 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005793 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005794 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005795 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796 }
5797 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005798 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799 }
5800
Prabir Pradhancef936d2021-07-21 16:17:52 +00005801 if (!mCommandQueue.empty()) {
5802 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5803 } else {
5804 dump += INDENT "CommandQueue: <empty>\n";
5805 }
5806
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005807 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005808 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005809 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005810 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005811 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005812 connection->inputChannel->getFd().get(),
5813 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005814 connection->getWindowName().c_str(),
5815 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005816 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005818 if (!connection->outboundQueue.empty()) {
5819 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5820 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005821 dump += dumpQueue(connection->outboundQueue, currentTime);
5822
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005824 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 }
5826
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005827 if (!connection->waitQueue.empty()) {
5828 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5829 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005830 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005832 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005834 std::stringstream inputStateDump;
5835 inputStateDump << connection->inputState;
5836 if (!isEmpty(inputStateDump)) {
5837 dump += INDENT3 "InputState: ";
5838 dump += inputStateDump.str() + "\n";
5839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 }
5841 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005842 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 }
5844
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005845 dump += "input_flags::remove_app_switch_drops() = ";
5846 dump += toString(input_flags::remove_app_switch_drops());
5847 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005849 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5850 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005852 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 }
5854
Antonio Kantek15beb512022-06-13 22:35:41 +00005855 if (!mTouchModePerDisplay.empty()) {
5856 dump += INDENT "TouchModePerDisplay:\n";
5857 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5858 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5859 std::to_string(touchMode).c_str());
5860 }
5861 } else {
5862 dump += INDENT "TouchModePerDisplay: <none>\n";
5863 }
5864
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005865 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005866 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5867 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5868 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005869 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005870 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871}
5872
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005873void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005874 const size_t numMonitors = monitors.size();
5875 for (size_t i = 0; i < numMonitors; i++) {
5876 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005877 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005878 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5879 dump += "\n";
5880 }
5881}
5882
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005883class LooperEventCallback : public LooperCallback {
5884public:
5885 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5886 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5887
5888private:
5889 std::function<int(int events)> mCallback;
5890};
5891
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005892Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005893 if (DEBUG_CHANNEL_CREATION) {
5894 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005897 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005898 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005899 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005900
5901 if (result) {
5902 return base::Error(result) << "Failed to open input channel pair with name " << name;
5903 }
5904
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005906 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005907 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005908 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005909 std::shared_ptr<Connection> connection =
5910 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5911 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005913 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5914 ALOGE("Created a new connection, but the token %p is already known", token.get());
5915 }
5916 mConnectionsByToken.emplace(token, connection);
5917
5918 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5919 this, std::placeholders::_1, token);
5920
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005921 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5922 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 } // release lock
5924
5925 // Wake the looper because some connections have changed.
5926 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005927 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928}
5929
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005930Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005931 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005932 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005933 std::shared_ptr<InputChannel> serverChannel;
5934 std::unique_ptr<InputChannel> clientChannel;
5935 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5936 if (result) {
5937 return base::Error(result) << "Failed to open input channel pair with name " << name;
5938 }
5939
Michael Wright3dd60e22019-03-27 22:06:44 +00005940 { // acquire lock
5941 std::scoped_lock _l(mLock);
5942
5943 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005944 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5945 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005946 }
5947
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005948 std::shared_ptr<Connection> connection =
5949 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005950 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005951 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005952
5953 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5954 ALOGE("Created a new connection, but the token %p is already known", token.get());
5955 }
5956 mConnectionsByToken.emplace(token, connection);
5957 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5958 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005959
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005960 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005961
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005962 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5963 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005964 }
Garfield Tan15601662020-09-22 15:32:38 -07005965
Michael Wright3dd60e22019-03-27 22:06:44 +00005966 // Wake the looper because some connections have changed.
5967 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005968 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005969}
5970
Garfield Tan15601662020-09-22 15:32:38 -07005971status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005973 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974
Harry Cutts33476232023-01-30 19:57:29 +00005975 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976 if (status) {
5977 return status;
5978 }
5979 } // release lock
5980
5981 // Wake the poll loop because removing the connection may have changed the current
5982 // synchronization state.
5983 mLooper->wake();
5984 return OK;
5985}
5986
Garfield Tan15601662020-09-22 15:32:38 -07005987status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5988 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005989 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005990 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005991 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992 return BAD_VALUE;
5993 }
5994
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005995 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005996
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005998 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005999 }
6000
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006001 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002
6003 nsecs_t currentTime = now();
6004 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6005
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006006 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007 return OK;
6008}
6009
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006010void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6012 auto& [displayId, monitors] = *it;
6013 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6014 return monitor.inputChannel->getConnectionToken() == connectionToken;
6015 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006016
Michael Wright3dd60e22019-03-27 22:06:44 +00006017 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006018 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006019 } else {
6020 ++it;
6021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 }
6023}
6024
Michael Wright3dd60e22019-03-27 22:06:44 +00006025status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006026 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006027 return pilferPointersLocked(token);
6028}
Michael Wright3dd60e22019-03-27 22:06:44 +00006029
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006030status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006031 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6032 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006033 LOG(WARNING)
6034 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006035 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006036 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006037
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006038 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006039 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006040 LOG(WARNING)
6041 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6042 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006043 return BAD_VALUE;
6044 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006045 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006046 if (deviceIds.empty()) {
6047 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006048 return BAD_VALUE;
6049 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006050
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006051 for (const DeviceId deviceId : deviceIds) {
6052 TouchState& state = *statePtr;
6053 TouchedWindow& window = *windowPtr;
6054 // Send cancel events to all the input channels we're stealing from.
6055 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6056 "input channel stole pointer stream");
6057 options.deviceId = deviceId;
6058 options.displayId = displayId;
6059 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6060 options.pointerIds = pointerIds;
6061 std::string canceledWindows;
6062 for (const TouchedWindow& w : state.windows) {
6063 const std::shared_ptr<InputChannel> channel =
6064 getInputChannelLocked(w.windowHandle->getToken());
6065 if (channel != nullptr && channel->getConnectionToken() != token) {
6066 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6067 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6068 canceledWindows += channel->getName();
6069 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006071 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6072 LOG(INFO) << "Channel " << requestingChannel->getName()
6073 << " is stealing input gesture for device " << deviceId << " from "
6074 << canceledWindows;
6075
6076 // Prevent the gesture from being sent to any other windows.
6077 // This only blocks relevant pointers to be sent to other windows
6078 window.addPilferingPointers(deviceId, pointerIds);
6079
6080 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006081 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006082 return OK;
6083}
6084
Prabir Pradhan99987712020-11-10 18:43:05 -08006085void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6086 { // acquire lock
6087 std::scoped_lock _l(mLock);
6088 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006089 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006090 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6091 windowHandle != nullptr ? windowHandle->getName().c_str()
6092 : "token without window");
6093 }
6094
Vishnu Nairc519ff72021-01-21 08:23:08 -08006095 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006096 if (focusedToken != windowToken) {
6097 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6098 enabled ? "enable" : "disable");
6099 return;
6100 }
6101
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006102 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006103 ALOGW("Ignoring request to %s Pointer Capture: "
6104 "window has %s requested pointer capture.",
6105 enabled ? "enable" : "disable", enabled ? "already" : "not");
6106 return;
6107 }
6108
Christine Franksb768bb42021-11-29 12:11:31 -08006109 if (enabled) {
6110 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6111 mIneligibleDisplaysForPointerCapture.end(),
6112 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6113 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6114 return;
6115 }
6116 }
6117
Prabir Pradhan99987712020-11-10 18:43:05 -08006118 setPointerCaptureLocked(enabled);
6119 } // release lock
6120
6121 // Wake the thread to process command entries.
6122 mLooper->wake();
6123}
6124
Christine Franksb768bb42021-11-29 12:11:31 -08006125void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6126 { // acquire lock
6127 std::scoped_lock _l(mLock);
6128 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6129 if (!isEligible) {
6130 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6131 }
6132 } // release lock
6133}
6134
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006135std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006136 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006137 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006138 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006139 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006140 }
6141 }
6142 }
6143 return std::nullopt;
6144}
6145
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006146std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6147 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006148 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006149 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006150 }
6151
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006152 for (const auto& [token, connection] : mConnectionsByToken) {
6153 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006154 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006155 }
6156 }
Robert Carr4e670e52018-08-15 13:26:12 -07006157
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006158 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159}
6160
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006161std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006162 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006163 if (connection == nullptr) {
6164 return "<nullptr>";
6165 }
6166 return connection->getInputChannelName();
6167}
6168
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006169void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006170 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006171 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006172}
6173
Prabir Pradhancef936d2021-07-21 16:17:52 +00006174void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006175 const std::shared_ptr<Connection>& connection,
6176 uint32_t seq, bool handled,
6177 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006178 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006179 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006180
6181 { // Start critical section
6182 auto dispatchEntryIt =
6183 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6184 [seq](auto& e) { return e->seq == seq; });
6185 if (dispatchEntryIt == connection->waitQueue.end()) {
6186 return;
6187 }
6188
6189 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6190
6191 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6192 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6193 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6194 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6195 }
6196 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6197 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6198 connection->inputChannel->getConnectionToken(),
6199 dispatchEntry.deliveryTime, consumeTime, finishTime);
6200 }
6201
6202 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6203 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6204 restartEvent =
6205 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6206 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6207 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6208 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6209 motionEntry, handled);
6210 } else {
6211 restartEvent = false;
6212 }
6213 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006214
6215 // Dequeue the event and start the next cycle.
6216 // Because the lock might have been released, it is possible that the
6217 // contents of the wait queue to have been drained, so we need to double-check
6218 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006219 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6220 [seq](auto& e) { return e->seq == seq; });
6221 if (entryIt != connection->waitQueue.end()) {
6222 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6223 connection->waitQueue.erase(entryIt);
6224
Prabir Pradhancef936d2021-07-21 16:17:52 +00006225 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6226 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6227 if (!connection->responsive) {
6228 connection->responsive = isConnectionResponsive(*connection);
6229 if (connection->responsive) {
6230 // The connection was unresponsive, and now it's responsive.
6231 processConnectionResponsiveLocked(*connection);
6232 }
6233 }
6234 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006235 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006236 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006237 traceOutboundQueueLength(*connection);
6238 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006239 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006240 }
6241 }
6242
6243 // Start the next dispatch cycle for this connection.
6244 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245}
6246
Prabir Pradhancef936d2021-07-21 16:17:52 +00006247void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6248 const sp<IBinder>& newToken) {
6249 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6250 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006251 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252 };
6253 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254}
6255
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6257 auto command = [this, token, x, y]() REQUIRES(mLock) {
6258 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006259 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006260 };
6261 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006262}
6263
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006264void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006265 if (connection == nullptr) {
6266 LOG_ALWAYS_FATAL("Caller must check for nullness");
6267 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006268 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6269 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006270 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006271 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006272 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006273 return;
6274 }
6275 /**
6276 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6277 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6278 * has changed. This could cause newer entries to time out before the already dispatched
6279 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6280 * processes the events linearly. So providing information about the oldest entry seems to be
6281 * most useful.
6282 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006283 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6284 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006285 std::string reason =
6286 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006287 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006288 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006289 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006290 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006291 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006292
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006293 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6294
6295 // Stop waking up for events on this connection, it is already unresponsive
6296 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006297}
6298
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006299void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6300 std::string reason =
6301 StringPrintf("%s does not have a focused window", application->getName().c_str());
6302 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303
Yabin Cui8eb9c552023-06-08 18:05:07 +00006304 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006306 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 };
6308 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006309}
6310
chaviw98318de2021-05-19 16:45:23 -05006311void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006312 const std::string& reason) {
6313 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6314 updateLastAnrStateLocked(windowLabel, reason);
6315}
6316
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006317void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6318 const std::string& reason) {
6319 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006320 updateLastAnrStateLocked(windowLabel, reason);
6321}
6322
6323void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6324 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006325 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006326 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006327 struct tm tm;
6328 localtime_r(&t, &tm);
6329 char timestr[64];
6330 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006331 mLastAnrState.clear();
6332 mLastAnrState += INDENT "ANR:\n";
6333 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006334 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6335 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006336 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006337}
6338
Prabir Pradhancef936d2021-07-21 16:17:52 +00006339void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6340 KeyEntry& entry) {
6341 const KeyEvent event = createKeyEvent(entry);
6342 nsecs_t delay = 0;
6343 { // release lock
6344 scoped_unlock unlock(mLock);
6345 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006346 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006347 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6348 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6349 std::to_string(t.duration().count()).c_str());
6350 }
6351 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352
6353 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006354 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006355 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006356 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006358 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006359 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361}
6362
Prabir Pradhancef936d2021-07-21 16:17:52 +00006363void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006364 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006365 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006366 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006367 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006368 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369 };
6370 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006371}
6372
Prabir Pradhanedd96402022-02-15 01:46:16 -08006373void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006374 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006375 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006376 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006377 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006378 };
6379 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006380}
6381
6382/**
6383 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6384 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6385 * command entry to the command queue.
6386 */
6387void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6388 std::string reason) {
6389 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006390 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006391 if (connection.monitor) {
6392 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6393 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006394 pid = findMonitorPidByTokenLocked(connectionToken);
6395 } else {
6396 // The connection is a window
6397 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6398 reason.c_str());
6399 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6400 if (handle != nullptr) {
6401 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006402 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006403 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006404 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006405}
6406
6407/**
6408 * Tell the policy that a connection has become responsive so that it can stop ANR.
6409 */
6410void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6411 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006412 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006413 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006414 pid = findMonitorPidByTokenLocked(connectionToken);
6415 } else {
6416 // The connection is a window
6417 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6418 if (handle != nullptr) {
6419 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006420 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006421 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006422 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006423}
6424
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006425bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006426 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006427 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006428 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006429 if (!handled) {
6430 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006431 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006432 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006433 return false;
6434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006436 // Get the fallback key state.
6437 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006438 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006439 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006440 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 connection->inputState.removeFallbackKey(originalKeyCode);
6442 }
6443
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006444 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006445 // If the application handles the original key for which we previously
6446 // generated a fallback or if the window is not a foreground window,
6447 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006448 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006449 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006450 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6451 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6452 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6453 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6454 keyEntry.policyFlags);
6455 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006456 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006458
6459 mLock.unlock();
6460
Prabir Pradhana41d2442023-04-20 21:30:40 +00006461 if (const auto unhandledKeyFallback =
6462 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6463 event, keyEntry.policyFlags);
6464 unhandledKeyFallback) {
6465 event = *unhandledKeyFallback;
6466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006467
6468 mLock.lock();
6469
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006470 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006471 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006472 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 "application handled the original non-fallback key "
6474 "or is no longer a foreground target, "
6475 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006476 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006477 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006478 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479 connection->inputState.removeFallbackKey(originalKeyCode);
6480 }
6481 } else {
6482 // If the application did not handle a non-fallback key, first check
6483 // that we are in a good state to perform unhandled key event processing
6484 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006485 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006486 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006487 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6488 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6489 "since this is not an initial down. "
6490 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6491 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6492 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006493 return false;
6494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006496 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006497 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6498 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6499 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6500 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6501 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006502 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503
6504 mLock.unlock();
6505
Prabir Pradhana41d2442023-04-20 21:30:40 +00006506 bool fallback = false;
6507 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6508 event, keyEntry.policyFlags);
6509 fb) {
6510 fallback = true;
6511 event = *fb;
6512 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513
6514 mLock.lock();
6515
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006516 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517 connection->inputState.removeFallbackKey(originalKeyCode);
6518 return false;
6519 }
6520
6521 // Latch the fallback keycode for this key on an initial down.
6522 // The fallback keycode cannot change at any other point in the lifecycle.
6523 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006525 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006526 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006527 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006528 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006529 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006530 }
6531
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533
6534 // Cancel the fallback key if the policy decides not to send it anymore.
6535 // We will continue to dispatch the key to the policy but we will no
6536 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006537 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6538 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006539 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6540 if (fallback) {
6541 ALOGD("Unhandled key event: Policy requested to send key %d"
6542 "as a fallback for %d, but on the DOWN it had requested "
6543 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006544 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006545 } else {
6546 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6547 "but on the DOWN it had requested to send %d. "
6548 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006549 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006550 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006551 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006552
Michael Wrightfb04fd52022-11-24 22:31:11 +00006553 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006554 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006555 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556 synthesizeCancelationEventsForConnectionLocked(connection, options);
6557
6558 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006559 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006560 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006561 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006562 }
6563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6566 {
6567 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006568 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006569 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006570 for (const auto& [key, value] : fallbackKeys) {
6571 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006572 }
6573 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6574 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006576 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006577
6578 if (fallback) {
6579 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006580 keyEntry.eventTime = event.getEventTime();
6581 keyEntry.deviceId = event.getDeviceId();
6582 keyEntry.source = event.getSource();
6583 keyEntry.displayId = event.getDisplayId();
6584 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006585 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006586 keyEntry.scanCode = event.getScanCode();
6587 keyEntry.metaState = event.getMetaState();
6588 keyEntry.repeatCount = event.getRepeatCount();
6589 keyEntry.downTime = event.getDownTime();
6590 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006591
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6593 ALOGD("Unhandled key event: Dispatching fallback key. "
6594 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006595 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006596 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006597 return true; // restart the event
6598 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006599 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6600 ALOGD("Unhandled key event: No fallback key.");
6601 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006602
6603 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006604 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006605 }
6606 }
6607 return false;
6608}
6609
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006610bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006611 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006612 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613 return false;
6614}
6615
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616void InputDispatcher::traceInboundQueueLengthLocked() {
6617 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006618 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619 }
6620}
6621
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006622void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623 if (ATRACE_ENABLED()) {
6624 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006625 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6626 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006627 }
6628}
6629
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006630void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 if (ATRACE_ENABLED()) {
6632 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006633 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6634 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635 }
6636}
6637
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006638void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006639 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006641 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006642 dumpDispatchStateLocked(dump);
6643
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006644 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006645 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006646 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647 }
6648}
6649
6650void InputDispatcher::monitor() {
6651 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006652 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006653 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006654 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006655}
6656
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006657/**
6658 * Wake up the dispatcher and wait until it processes all events and commands.
6659 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6660 * this method can be safely called from any thread, as long as you've ensured that
6661 * the work you are interested in completing has already been queued.
6662 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006663bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006664 /**
6665 * Timeout should represent the longest possible time that a device might spend processing
6666 * events and commands.
6667 */
6668 constexpr std::chrono::duration TIMEOUT = 100ms;
6669 std::unique_lock lock(mLock);
6670 mLooper->wake();
6671 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6672 return result == std::cv_status::no_timeout;
6673}
6674
Vishnu Naire798b472020-07-23 13:52:21 -07006675/**
6676 * Sets focus to the window identified by the token. This must be called
6677 * after updating any input window handles.
6678 *
6679 * Params:
6680 * request.token - input channel token used to identify the window that should gain focus.
6681 * request.focusedToken - the token that the caller expects currently to be focused. If the
6682 * specified token does not match the currently focused window, this request will be dropped.
6683 * If the specified focused token matches the currently focused window, the call will succeed.
6684 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6685 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6686 * when requesting the focus change. This determines which request gets
6687 * precedence if there is a focus change request from another source such as pointer down.
6688 */
Vishnu Nair958da932020-08-21 17:12:37 -07006689void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6690 { // acquire lock
6691 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006692 std::optional<FocusResolver::FocusChanges> changes =
6693 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6694 if (changes) {
6695 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006696 }
6697 } // release lock
6698 // Wake up poll loop since it may need to make new input dispatching choices.
6699 mLooper->wake();
6700}
6701
Vishnu Nairc519ff72021-01-21 08:23:08 -08006702void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6703 if (changes.oldFocus) {
6704 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006705 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006706 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006707 "focus left window");
6708 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006709 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006710 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006711 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006712 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006713 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006714 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006715 }
6716
Prabir Pradhan99987712020-11-10 18:43:05 -08006717 // If a window has pointer capture, then it must have focus. We need to ensure that this
6718 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6719 // If the window loses focus before it loses pointer capture, then the window can be in a state
6720 // where it has pointer capture but not focus, violating the contract. Therefore we must
6721 // dispatch the pointer capture event before the focus event. Since focus events are added to
6722 // the front of the queue (above), we add the pointer capture event to the front of the queue
6723 // after the focus events are added. This ensures the pointer capture event ends up at the
6724 // front.
6725 disablePointerCaptureForcedLocked();
6726
Vishnu Nairc519ff72021-01-21 08:23:08 -08006727 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006728 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006729 }
6730}
Vishnu Nair958da932020-08-21 17:12:37 -07006731
Prabir Pradhan99987712020-11-10 18:43:05 -08006732void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006733 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006734 return;
6735 }
6736
6737 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6738
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006739 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006740 setPointerCaptureLocked(false);
6741 }
6742
6743 if (!mWindowTokenWithPointerCapture) {
6744 // No need to send capture changes because no window has capture.
6745 return;
6746 }
6747
6748 if (mPendingEvent != nullptr) {
6749 // Move the pending event to the front of the queue. This will give the chance
6750 // for the pending event to be dropped if it is a captured event.
6751 mInboundQueue.push_front(mPendingEvent);
6752 mPendingEvent = nullptr;
6753 }
6754
6755 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006756 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006757 mInboundQueue.push_front(std::move(entry));
6758}
6759
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006760void InputDispatcher::setPointerCaptureLocked(bool enable) {
6761 mCurrentPointerCaptureRequest.enable = enable;
6762 mCurrentPointerCaptureRequest.seq++;
6763 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006764 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006765 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006766 };
6767 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006768}
6769
Vishnu Nair599f1412021-06-21 10:39:58 -07006770void InputDispatcher::displayRemoved(int32_t displayId) {
6771 { // acquire lock
6772 std::scoped_lock _l(mLock);
6773 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006774 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006775 setFocusedApplicationLocked(displayId, nullptr);
6776 // Call focus resolver to clean up stale requests. This must be called after input windows
6777 // have been removed for the removed display.
6778 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006779 // Reset pointer capture eligibility, regardless of previous state.
6780 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006781 // Remove the associated touch mode state.
6782 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006783 mVerifiersByDisplay.erase(displayId);
Siarhei Vishniakou96e4fad2023-09-20 09:30:44 -07006784 mInputFilterVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006785 } // release lock
6786
6787 // Wake up poll loop since it may need to make new input dispatching choices.
6788 mLooper->wake();
6789}
6790
Patrick Williamsd828f302023-04-28 17:52:08 -05006791void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006792 // The listener sends the windows as a flattened array. Separate the windows by display for
6793 // more convenient parsing.
6794 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006795 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006796 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006797 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006798 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006799
6800 { // acquire lock
6801 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006802
6803 // Ensure that we have an entry created for all existing displays so that if a displayId has
6804 // no windows, we can tell that the windows were removed from the display.
6805 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6806 handlesPerDisplay[displayId];
6807 }
6808
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006809 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006810 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006811 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6812 }
6813
6814 for (const auto& [displayId, handles] : handlesPerDisplay) {
6815 setInputWindowsLocked(handles, displayId);
6816 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006817
6818 if (update.vsyncId < mWindowInfosVsyncId) {
6819 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6820 ", current update vsync id: %" PRId64,
6821 mWindowInfosVsyncId, update.vsyncId);
6822 }
6823 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006824 }
6825 // Wake up poll loop since it may need to make new input dispatching choices.
6826 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006827}
6828
Vishnu Nair062a8672021-09-03 16:07:44 -07006829bool InputDispatcher::shouldDropInput(
6830 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006831 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6832 (windowHandle->getInfo()->inputConfig.test(
6833 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006834 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006835 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6836 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006837 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006838 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006839 windowHandle->getInfo()->displayId);
6840 return true;
6841 }
6842 return false;
6843}
6844
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006845void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006846 const gui::WindowInfosUpdate& update) {
6847 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006848}
6849
Arthur Hungdfd528e2021-12-08 13:23:04 +00006850void InputDispatcher::cancelCurrentTouch() {
6851 {
6852 std::scoped_lock _l(mLock);
6853 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006854 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006855 "cancel current touch");
6856 synthesizeCancelationEventsForAllConnectionsLocked(options);
6857
6858 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006859 }
6860 // Wake up poll loop since there might be work to do.
6861 mLooper->wake();
6862}
6863
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006864void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6865 std::scoped_lock _l(mLock);
6866 mMonitorDispatchingTimeout = timeout;
6867}
6868
Arthur Hungc539dbb2022-12-08 07:45:36 +00006869void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6870 const sp<WindowInfoHandle>& oldWindowHandle,
6871 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006872 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006873 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006874 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6875 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006876 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6877 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6878 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6879 newWindowHandle->getInfo()->inputConfig.test(
6880 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6881 const sp<WindowInfoHandle> oldWallpaper =
6882 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6883 const sp<WindowInfoHandle> newWallpaper =
6884 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6885 if (oldWallpaper == newWallpaper) {
6886 return;
6887 }
6888
6889 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006890 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006891 addPointerWindowTargetLocked(oldWallpaper,
6892 oldTouchedWindow.targetFlags |
6893 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6894 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId),
6895 targets);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006896 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006897 }
6898
6899 if (newWallpaper != nullptr) {
6900 state.addOrUpdateWindow(newWallpaper,
6901 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6902 InputTarget::Flags::WINDOW_IS_OBSCURED |
6903 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006904 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006905 }
6906}
6907
6908void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6909 ftl::Flags<InputTarget::Flags> newTargetFlags,
6910 const sp<WindowInfoHandle> fromWindowHandle,
6911 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006912 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006913 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006914 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6915 fromWindowHandle->getInfo()->inputConfig.test(
6916 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6917 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6918 toWindowHandle->getInfo()->inputConfig.test(
6919 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6920
6921 const sp<WindowInfoHandle> oldWallpaper =
6922 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6923 const sp<WindowInfoHandle> newWallpaper =
6924 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6925 if (oldWallpaper == newWallpaper) {
6926 return;
6927 }
6928
6929 if (oldWallpaper != nullptr) {
6930 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6931 "transferring touch focus to another window");
6932 state.removeWindowByToken(oldWallpaper->getToken());
6933 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6934 }
6935
6936 if (newWallpaper != nullptr) {
6937 nsecs_t downTimeInTarget = now();
6938 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6939 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6940 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6941 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006942 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6943 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006944 std::shared_ptr<Connection> wallpaperConnection =
6945 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006946 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006947 std::shared_ptr<Connection> toConnection =
6948 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006949 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6950 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6951 wallpaperFlags);
6952 }
6953 }
6954}
6955
6956sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6957 const sp<WindowInfoHandle>& windowHandle) const {
6958 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6959 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6960 bool foundWindow = false;
6961 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6962 if (!foundWindow && otherHandle != windowHandle) {
6963 continue;
6964 }
6965 if (windowHandle == otherHandle) {
6966 foundWindow = true;
6967 continue;
6968 }
6969
6970 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6971 return otherHandle;
6972 }
6973 }
6974 return nullptr;
6975}
6976
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006977void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6978 std::scoped_lock _l(mLock);
6979
6980 mConfig.keyRepeatTimeout = timeout;
6981 mConfig.keyRepeatDelay = delay;
6982}
6983
Garfield Tane84e6f92019-08-29 17:28:41 -07006984} // namespace android::inputdispatcher