blob: d0a72eee20c843dd746ae6b35701c2e5052e7fad [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;
368 pointerCoords.resize(motionEntry.pointerCount);
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.
378 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
379 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,
402 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000403 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404
405 if (motionEntry.injectionState) {
406 combinedMotionEntry->injectionState = motionEntry.injectionState;
407 combinedMotionEntry->injectionState->refCount += 1;
408 }
409
410 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700411 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700412 firstPointerTransform, inputTarget.displayTransform,
413 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000414 return dispatchEntry;
415}
416
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000417status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
418 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700419 std::unique_ptr<InputChannel> uniqueServerChannel;
420 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
421
422 serverChannel = std::move(uniqueServerChannel);
423 return result;
424}
425
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500426template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000427bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500428 if (lhs == nullptr && rhs == nullptr) {
429 return true;
430 }
431 if (lhs == nullptr || rhs == nullptr) {
432 return false;
433 }
434 return *lhs == *rhs;
435}
436
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000437KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000438 KeyEvent event;
439 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
440 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
441 entry.repeatCount, entry.downTime, entry.eventTime);
442 return event;
443}
444
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000445bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000446 // Do not keep track of gesture monitors. They receive every event and would disproportionately
447 // affect the statistics.
448 if (connection.monitor) {
449 return false;
450 }
451 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
452 if (!connection.responsive) {
453 return false;
454 }
455 return true;
456}
457
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000458bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000459 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
460 const int32_t& inputEventId = eventEntry.id;
461 if (inputEventId != dispatchEntry.resolvedEventId) {
462 // Event was transmuted
463 return false;
464 }
465 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
466 return false;
467 }
468 // Only track latency for events that originated from hardware
469 if (eventEntry.isSynthesized()) {
470 return false;
471 }
472 const EventEntry::Type& inputEventEntryType = eventEntry.type;
473 if (inputEventEntryType == EventEntry::Type::KEY) {
474 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
475 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
476 return false;
477 }
478 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
479 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
480 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
481 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
482 return false;
483 }
484 } else {
485 // Not a key or a motion
486 return false;
487 }
488 if (!shouldReportMetricsForConnection(connection)) {
489 return false;
490 }
491 return true;
492}
493
Prabir Pradhancef936d2021-07-21 16:17:52 +0000494/**
495 * Connection is responsive if it has no events in the waitQueue that are older than the
496 * current time.
497 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000498bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000499 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000500 for (const auto& dispatchEntry : connection.waitQueue) {
501 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000502 return false;
503 }
504 }
505 return true;
506}
507
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508// Returns true if the event type passed as argument represents a user activity.
509bool isUserActivityEvent(const EventEntry& eventEntry) {
510 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000511 case EventEntry::Type::CONFIGURATION_CHANGED:
512 case EventEntry::Type::DEVICE_RESET:
513 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 case EventEntry::Type::FOCUS:
515 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000516 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000517 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000519 case EventEntry::Type::KEY:
520 case EventEntry::Type::MOTION:
521 return true;
522 }
523}
524
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800525// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000526bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000527 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800528 const auto inputConfig = windowInfo.inputConfig;
529 if (windowInfo.displayId != displayId ||
530 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800531 return false;
532 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700533 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800534 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800535 return false;
536 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000537
538 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
539 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
540 // the window. Points on the right and bottom edges should not be inside the window, so we need
541 // to be careful about performing a hit test when the display is rotated, since the "right" and
542 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
543 // logical display in which WM determined the bounds. Perform the hit test in the logical
544 // display space to ensure these edges are considered correctly in all orientations.
545 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
546 const auto p = displayTransform.transform(x, y);
547 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800548 return false;
549 }
550 return true;
551}
552
Prabir Pradhand65552b2021-10-07 11:23:50 -0700553bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
554 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000555 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700556}
557
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800558// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000559// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
560// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
561// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800562// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000563bool canReceiveForegroundTouches(const WindowInfo& info) {
564 // A non-touchable window can still receive touch events (e.g. in the case of
565 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
566 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
567}
568
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000569bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700570 if (windowHandle == nullptr) {
571 return false;
572 }
573 const WindowInfo* windowInfo = windowHandle->getInfo();
574 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
575 return true;
576 }
577 return false;
578}
579
Prabir Pradhan5735a322022-04-11 17:23:34 +0000580// Checks targeted injection using the window's owner's uid.
581// Returns an empty string if an entry can be sent to the given window, or an error message if the
582// entry is a targeted injection whose uid target doesn't match the window owner.
583std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
584 const EventEntry& entry) {
585 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
586 // The event was not injected, or the injected event does not target a window.
587 return {};
588 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000589 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000590 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000591 return StringPrintf("No valid window target for injection into uid %s.",
592 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000593 }
594 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000595 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
596 "owned by uid %s.",
597 uid.toString().c_str(), window->getName().c_str(),
598 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000599 }
600 return {};
601}
602
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000603std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700604 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
605 // Always dispatch mouse events to cursor position.
606 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000607 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700608 }
609
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700610 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000611 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
612 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700613}
614
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700615std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
616 if (eventEntry.type == EventEntry::Type::KEY) {
617 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
618 return keyEntry.downTime;
619 } else if (eventEntry.type == EventEntry::Type::MOTION) {
620 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
621 return motionEntry.downTime;
622 }
623 return std::nullopt;
624}
625
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000626/**
627 * Compare the old touch state to the new touch state, and generate the corresponding touched
628 * windows (== input targets).
629 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
630 * If the pointer just entered the new window, produce HOVER_ENTER.
631 * For pointers remaining in the window, produce HOVER_MOVE.
632 */
633std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
634 const TouchState& newTouchState,
635 const MotionEntry& entry) {
636 std::vector<TouchedWindow> out;
637 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
638 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
639 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
640 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
641 // Not a hover event - don't need to do anything
642 return out;
643 }
644
645 // We should consider all hovering pointers here. But for now, just use the first one
646 const int32_t pointerId = entry.pointerProperties[0].id;
647
648 std::set<sp<WindowInfoHandle>> oldWindows;
649 if (oldState != nullptr) {
650 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
651 }
652
653 std::set<sp<WindowInfoHandle>> newWindows =
654 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
655
656 // If the pointer is no longer in the new window set, send HOVER_EXIT.
657 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
658 if (newWindows.find(oldWindow) == newWindows.end()) {
659 TouchedWindow touchedWindow;
660 touchedWindow.windowHandle = oldWindow;
661 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000662 out.push_back(touchedWindow);
663 }
664 }
665
666 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
667 TouchedWindow touchedWindow;
668 touchedWindow.windowHandle = newWindow;
669 if (oldWindows.find(newWindow) == oldWindows.end()) {
670 // Any windows that have this pointer now, and didn't have it before, should get
671 // HOVER_ENTER
672 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
673 } else {
674 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700675 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700676 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000677 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
678 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700679 // The Accessibility injected touch exploration event stream
680 // has known inconsistencies, so log ERROR instead of
681 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700682 severity = android::base::LogSeverity::ERROR;
683 }
684 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700685 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000686 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
687 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700688 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000689 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
690 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
691 }
692 out.push_back(touchedWindow);
693 }
694 return out;
695}
696
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800697template <typename T>
698std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
699 left.insert(left.end(), right.begin(), right.end());
700 return left;
701}
702
Harry Cuttsb166c002023-05-09 13:06:05 +0000703// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
704// both.
705void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
706 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
707 if (!window.windowHandle->getInfo()->inputConfig.test(
708 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
709 // In addition to TouchState, erase this window from the input targets! We don't have a
710 // good way to do this today except by adding a nested loop.
711 // TODO(b/282025641): simplify this code once InputTargets are being identified
712 // separately from TouchedWindows.
713 std::erase_if(targets, [&](const InputTarget& target) {
714 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
715 });
716 return true;
717 }
718 return false;
719 });
720}
721
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700722/**
723 * In general, touch should be always split between windows. Some exceptions:
724 * 1. Don't split touch if all of the below is true:
725 * (a) we have an active pointer down *and*
726 * (b) a new pointer is going down that's from the same device *and*
727 * (c) the window that's receiving the current pointer does not support split touch.
728 * 2. Don't split mouse events
729 */
730bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
731 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
732 // We should never split mouse events
733 return false;
734 }
735 for (const TouchedWindow& touchedWindow : touchState.windows) {
736 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
737 // Spy windows should not affect whether or not touch is split.
738 continue;
739 }
740 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
741 continue;
742 }
743 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
744 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
745 // Wallpaper window should not affect whether or not touch is split
746 continue;
747 }
748
749 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
750 return false;
751 }
752 }
753 return true;
754}
755
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000756} // namespace
757
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758// --- InputDispatcher ---
759
Prabir Pradhana41d2442023-04-20 21:30:40 +0000760InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800761 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
762
Prabir Pradhana41d2442023-04-20 21:30:40 +0000763InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800764 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700765 : mPolicy(policy),
766 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800768 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700770 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700771 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800772 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700773 mDispatchEnabled(false),
774 mDispatchFrozen(false),
775 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100776 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000777 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800778 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800779 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000780 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000781 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700782 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800783 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700785 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700786#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700787 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700788#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700789 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790}
791
792InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000793 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794
Prabir Pradhancef936d2021-07-21 16:17:52 +0000795 resetKeyRepeatLocked();
796 releasePendingEventLocked();
797 drainInboundQueueLocked();
798 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000800 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700801 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000802 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804}
805
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700806status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700807 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700808 return ALREADY_EXISTS;
809 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700810 mThread = std::make_unique<InputThread>(
811 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
812 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700813}
814
815status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700816 if (mThread && mThread->isCallingThread()) {
817 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700818 return INVALID_OPERATION;
819 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700820 mThread.reset();
821 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700822}
823
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700825 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800827 std::scoped_lock _l(mLock);
828 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829
830 // Run a dispatch loop if there are no pending commands.
831 // The dispatch loop might enqueue commands to run afterwards.
832 if (!haveCommandsLocked()) {
833 dispatchOnceInnerLocked(&nextWakeupTime);
834 }
835
836 // Run all pending commands if there are any.
837 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000838 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700839 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800841
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700842 // If we are still waiting for ack on some events,
843 // we might have to wake up earlier to check if an app is anr'ing.
844 const nsecs_t nextAnrCheck = processAnrsLocked();
845 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
846
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800847 // We are about to enter an infinitely long sleep, because we have no commands or
848 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700849 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800850 mDispatcherEnteredIdle.notify_all();
851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 } // release lock
853
854 // Wait for callback or timeout or wake. (make sure we round up, not down)
855 nsecs_t currentTime = now();
856 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
857 mLooper->pollOnce(timeoutMillis);
858}
859
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700860/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500861 * Raise ANR if there is no focused window.
862 * Before the ANR is raised, do a final state check:
863 * 1. The currently focused application must be the same one we are waiting for.
864 * 2. Ensure we still don't have a focused window.
865 */
866void InputDispatcher::processNoFocusedWindowAnrLocked() {
867 // Check if the application that we are waiting for is still focused.
868 std::shared_ptr<InputApplicationHandle> focusedApplication =
869 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
870 if (focusedApplication == nullptr ||
871 focusedApplication->getApplicationToken() !=
872 mAwaitedFocusedApplication->getApplicationToken()) {
873 // Unexpected because we should have reset the ANR timer when focused application changed
874 ALOGE("Waited for a focused window, but focused application has already changed to %s",
875 focusedApplication->getName().c_str());
876 return; // The focused application has changed.
877 }
878
chaviw98318de2021-05-19 16:45:23 -0500879 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500880 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
881 if (focusedWindowHandle != nullptr) {
882 return; // We now have a focused window. No need for ANR.
883 }
884 onAnrLocked(mAwaitedFocusedApplication);
885}
886
887/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700888 * Check if any of the connections' wait queues have events that are too old.
889 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
890 * Return the time at which we should wake up next.
891 */
892nsecs_t InputDispatcher::processAnrsLocked() {
893 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700894 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
896 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
897 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500898 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700899 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500900 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700901 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700902 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500903 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
905 }
906 }
907
908 // Check if any connection ANRs are due
909 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
910 if (currentTime < nextAnrCheck) { // most likely scenario
911 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
912 }
913
914 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700915 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700916 if (connection == nullptr) {
917 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
918 return nextAnrCheck;
919 }
920 connection->responsive = false;
921 // Stop waking up for this unresponsive connection
922 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000923 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700924 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925}
926
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800927std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700928 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800929 if (connection->monitor) {
930 return mMonitorDispatchingTimeout;
931 }
932 const sp<WindowInfoHandle> window =
933 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500935 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500937 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938}
939
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
941 nsecs_t currentTime = now();
942
Jeff Browndc5992e2014-04-11 01:27:26 -0700943 // Reset the key repeat timer whenever normal dispatch is suspended while the
944 // device is in a non-interactive state. This is to ensure that we abort a key
945 // repeat if the device is just coming out of sleep.
946 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 resetKeyRepeatLocked();
948 }
949
950 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
951 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100952 if (DEBUG_FOCUS) {
953 ALOGD("Dispatch frozen. Waiting some more.");
954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 return;
956 }
957
958 // Optimize latency of app switches.
959 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
960 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
961 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
962 if (mAppSwitchDueTime < *nextWakeupTime) {
963 *nextWakeupTime = mAppSwitchDueTime;
964 }
965
966 // Ready to start a new event.
967 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700969 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 if (isAppSwitchDue) {
971 // The inbound queue is empty so the app switch key we were waiting
972 // for will never arrive. Stop waiting for it.
973 resetPendingAppSwitchLocked(false);
974 isAppSwitchDue = false;
975 }
976
977 // Synthesize a key repeat if appropriate.
978 if (mKeyRepeatState.lastKeyEntry) {
979 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
980 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
981 } else {
982 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
983 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
984 }
985 }
986 }
987
988 // Nothing to do if there is no pending event.
989 if (!mPendingEvent) {
990 return;
991 }
992 } else {
993 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700994 mPendingEvent = mInboundQueue.front();
995 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 traceInboundQueueLengthLocked();
997 }
998
999 // Poke user activity for this event.
1000 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001001 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004
1005 // Now we have an event to dispatch.
1006 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001007 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001013 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001017 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 }
1019
1020 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001021 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001022 const ConfigurationChangedEntry& typedEntry =
1023 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001025 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 break;
1027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001029 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001030 const DeviceResetEntry& typedEntry =
1031 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001033 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 break;
1035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001037 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001038 std::shared_ptr<FocusEntry> typedEntry =
1039 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001040 dispatchFocusLocked(currentTime, typedEntry);
1041 done = true;
1042 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1043 break;
1044 }
1045
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001046 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1047 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1048 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1049 done = true;
1050 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1051 break;
1052 }
1053
Prabir Pradhan99987712020-11-10 18:43:05 -08001054 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1055 const auto typedEntry =
1056 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1057 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1058 done = true;
1059 break;
1060 }
1061
arthurhungb89ccb02020-12-30 16:19:01 +08001062 case EventEntry::Type::DRAG: {
1063 std::shared_ptr<DragEntry> typedEntry =
1064 std::static_pointer_cast<DragEntry>(mPendingEvent);
1065 dispatchDragLocked(currentTime, typedEntry);
1066 done = true;
1067 break;
1068 }
1069
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001070 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001073 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 resetPendingAppSwitchLocked(true);
1075 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 } else if (dropReason == DropReason::NOT_DROPPED) {
1077 dropReason = DropReason::APP_SWITCH;
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 Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1094 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001096 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1100 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001102 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
Chris Yef59a2f42020-10-16 12:55:26 -07001105
1106 case EventEntry::Type::SENSOR: {
1107 std::shared_ptr<SensorEntry> sensorEntry =
1108 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1109 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1110 dropReason = DropReason::APP_SWITCH;
1111 }
1112 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1113 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1114 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1115 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1116 dropReason = DropReason::STALE;
1117 }
1118 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1119 done = true;
1120 break;
1121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
1123
1124 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001125 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001126 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
Michael Wright3a981722015-06-10 15:26:13 +01001128 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129
1130 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001131 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
1133}
1134
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001135bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1136 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1137}
1138
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001139/**
1140 * Return true if the events preceding this incoming motion event should be dropped
1141 * Return false otherwise (the default behaviour)
1142 */
1143bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001144 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001145 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001146
1147 // Optimize case where the current application is unresponsive and the user
1148 // decides to touch a window in a different application.
1149 // If the application takes too long to catch up then we drop all events preceding
1150 // the touch into the other window.
1151 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001152 const int32_t displayId = motionEntry.displayId;
1153 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001154 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001155
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001156 sp<WindowInfoHandle> touchedWindowHandle =
1157 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001158 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001159 touchedWindowHandle->getApplicationToken() !=
1160 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001161 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001162 ALOGI("Pruning input queue because user touched a different application while waiting "
1163 "for %s",
1164 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001165 return true;
1166 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001167
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001168 // Alternatively, maybe there's a spy window that could handle this event.
1169 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1170 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1171 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001172 const std::shared_ptr<Connection> connection =
1173 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001174 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001175 // This spy window could take more input. Drop all events preceding this
1176 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001177 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001178 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001179 mAwaitedFocusedApplication->getName().c_str());
1180 return true;
1181 }
1182 }
1183 }
1184
1185 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1186 // yet been processed by some connections, the dispatcher will wait for these motion
1187 // events to be processed before dispatching the key event. This is because these motion events
1188 // may cause a new window to be launched, which the user might expect to receive focus.
1189 // To prevent waiting forever for such events, just send the key to the currently focused window
1190 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1191 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1192 "just send the pending key event to the focused window.");
1193 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001194 }
1195 return false;
1196}
1197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001199 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 mInboundQueue.push_back(std::move(newEntry));
1201 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 traceInboundQueueLengthLocked();
1203
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001205 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001206 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1207 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001208 // Optimize app switch latency.
1209 // If the application takes too long to catch up then we drop all events preceding
1210 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001215 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001217 if (DEBUG_APP_SWITCH) {
1218 ALOGD("App switch is pending!");
1219 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001220 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 mAppSwitchSawKeyDown = false;
1222 needWake = true;
1223 }
1224 }
1225 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001226
1227 // If a new up event comes in, and the pending event with same key code has been asked
1228 // to try again later because of the policy. We have to reset the intercept key wake up
1229 // time for it may have been handled in the policy and could be dropped.
1230 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1231 mPendingEvent->type == EventEntry::Type::KEY) {
1232 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1233 if (pendingKey.keyCode == keyEntry.keyCode &&
1234 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001235 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1236 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001237 pendingKey.interceptKeyWakeupTime = 0;
1238 needWake = true;
1239 }
1240 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 break;
1242 }
1243
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001244 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001245 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1246 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1248 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001249 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001253 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1255 break;
1256 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001257 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001258 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001259 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001260 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001261 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1262 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001263 // nothing to do
1264 break;
1265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267
1268 return needWake;
1269}
1270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001272 // Do not store sensor event in recent queue to avoid flooding the queue.
1273 if (entry->type != EventEntry::Type::SENSOR) {
1274 mRecentQueue.push_back(entry);
1275 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001276 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001277 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
1279}
1280
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001281sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1282 bool isStylus,
1283 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001285 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001286 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001287 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001288 continue;
1289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001291 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001292 if (!info.isSpy() &&
1293 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001294 return windowHandle;
1295 }
1296 }
1297 return nullptr;
1298}
1299
1300std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001301 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001302 if (touchedWindow == nullptr) {
1303 return {};
1304 }
1305 // Traverse windows from front to back until we encounter the touched window.
1306 std::vector<InputTarget> outsideTargets;
1307 const auto& windowHandles = getWindowHandlesLocked(displayId);
1308 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1309 if (windowHandle == touchedWindow) {
1310 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1311 // below the touched window will not get ACTION_OUTSIDE event.
1312 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001313 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001314
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001315 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001316 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001317 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1318 pointerIds.set(pointerId);
1319 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1320 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001323 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324}
1325
Prabir Pradhand65552b2021-10-07 11:23:50 -07001326std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001327 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001328 // Traverse windows from front to back and gather the touched spy windows.
1329 std::vector<sp<WindowInfoHandle>> spyWindows;
1330 const auto& windowHandles = getWindowHandlesLocked(displayId);
1331 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1332 const WindowInfo& info = *windowHandle->getInfo();
1333
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001334 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001335 continue;
1336 }
1337 if (!info.isSpy()) {
1338 // The first touched non-spy window was found, so return the spy windows touched so far.
1339 return spyWindows;
1340 }
1341 spyWindows.push_back(windowHandle);
1342 }
1343 return spyWindows;
1344}
1345
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001346void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 const char* reason;
1348 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001349 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001350 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001351 ALOGD("Dropped event because policy consumed it.");
1352 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 reason = "inbound event was dropped because the policy consumed it";
1354 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001355 case DropReason::DISABLED:
1356 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001357 ALOGI("Dropped event because input dispatch is disabled.");
1358 }
1359 reason = "inbound event was dropped because input dispatch is disabled";
1360 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001361 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 ALOGI("Dropped event because of pending overdue app switch.");
1363 reason = "inbound event was dropped because of pending overdue app switch";
1364 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001365 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001366 ALOGI("Dropped event because the current application is not responding and the user "
1367 "has started interacting with a different application.");
1368 reason = "inbound event was dropped because the current application is not responding "
1369 "and the user has started interacting with a different application";
1370 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001371 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001372 ALOGI("Dropped event because it is stale.");
1373 reason = "inbound event was dropped because it is stale";
1374 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 case DropReason::NO_POINTER_CAPTURE:
1376 ALOGI("Dropped event because there is no window with Pointer Capture.");
1377 reason = "inbound event was dropped because there is no window with Pointer Capture";
1378 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001379 case DropReason::NOT_DROPPED: {
1380 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 }
1384
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001385 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001386 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001387 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001391 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1393 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001394 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001395 synthesizeCancelationEventsForAllConnectionsLocked(options);
1396 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001397 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1398 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001399 synthesizeCancelationEventsForAllConnectionsLocked(options);
1400 }
1401 break;
1402 }
Chris Yef59a2f42020-10-16 12:55:26 -07001403 case EventEntry::Type::SENSOR: {
1404 break;
1405 }
arthurhungb89ccb02020-12-30 16:19:01 +08001406 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1407 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001408 break;
1409 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001410 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001411 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001414 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001415 break;
1416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 }
1418}
1419
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001420static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001421 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1422 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423}
1424
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001425bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1426 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1427 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1428 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001431bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001432 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433}
1434
1435void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001436 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001438 if (DEBUG_APP_SWITCH) {
1439 if (handled) {
1440 ALOGD("App switch has arrived.");
1441 } else {
1442 ALOGD("App switch was abandoned.");
1443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445}
1446
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001448 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449}
1450
Prabir Pradhancef936d2021-07-21 16:17:52 +00001451bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001452 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 return false;
1454 }
1455
1456 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001457 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001458 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001459 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1460 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001461 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 return true;
1463}
1464
Prabir Pradhancef936d2021-07-21 16:17:52 +00001465void InputDispatcher::postCommandLocked(Command&& command) {
1466 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467}
1468
1469void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001470 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001471 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001472 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 releaseInboundEventLocked(entry);
1474 }
1475 traceInboundQueueLengthLocked();
1476}
1477
1478void InputDispatcher::releasePendingEventLocked() {
1479 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001481 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 }
1483}
1484
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001485void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001488 if (DEBUG_DISPATCH_CYCLE) {
1489 ALOGD("Injected inbound event was dropped.");
1490 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001491 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 }
1493 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001494 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
1496 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497}
1498
1499void InputDispatcher::resetKeyRepeatLocked() {
1500 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001501 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503}
1504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001505std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1506 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507
Michael Wright2e732952014-09-24 13:26:59 -07001508 uint32_t policyFlags = entry->policyFlags &
1509 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 std::shared_ptr<KeyEntry> newEntry =
1512 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1513 entry->source, entry->displayId, policyFlags, entry->action,
1514 entry->flags, entry->keyCode, entry->scanCode,
1515 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001517 newEntry->syntheticRepeat = true;
1518 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521}
1522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001523bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001524 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001525 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1526 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528
1529 // Reset key repeating in case a keyboard device was added or removed or something.
1530 resetKeyRepeatLocked();
1531
1532 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001533 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1534 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001535 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001536 };
1537 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return true;
1539}
1540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001541bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1542 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001543 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1544 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1545 entry.deviceId);
1546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547
liushenxiang42232912021-05-21 20:24:09 +08001548 // Reset key repeating in case a keyboard device was disabled or enabled.
1549 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1550 resetKeyRepeatLocked();
1551 }
1552
Michael Wrightfb04fd52022-11-24 22:31:11 +00001553 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001556
1557 // Remove all active pointers from this device
1558 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1559 touchState.removeAllPointersForDevice(entry.deviceId);
1560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 return true;
1562}
1563
Vishnu Nairad321cd2020-08-20 16:40:21 -07001564void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001565 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001566 if (mPendingEvent != nullptr) {
1567 // Move the pending event to the front of the queue. This will give the chance
1568 // for the pending event to get dispatched to the newly focused window
1569 mInboundQueue.push_front(mPendingEvent);
1570 mPendingEvent = nullptr;
1571 }
1572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 std::unique_ptr<FocusEntry> focusEntry =
1574 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1575 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001576
1577 // This event should go to the front of the queue, but behind all other focus events
1578 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001579 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001580 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 [](const std::shared_ptr<EventEntry>& event) {
1582 return event->type == EventEntry::Type::FOCUS;
1583 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001584
1585 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001586 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001587}
1588
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001589void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001590 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001591 if (channel == nullptr) {
1592 return; // Window has gone away
1593 }
1594 InputTarget target;
1595 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001596 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001597 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001598 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1599 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001600 std::string reason = std::string("reason=").append(entry->reason);
1601 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001602 dispatchEventLocked(currentTime, entry, {target});
1603}
1604
Prabir Pradhan99987712020-11-10 18:43:05 -08001605void InputDispatcher::dispatchPointerCaptureChangedLocked(
1606 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1607 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001608 dropReason = DropReason::NOT_DROPPED;
1609
Prabir Pradhan99987712020-11-10 18:43:05 -08001610 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001611 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001612
1613 if (entry->pointerCaptureRequest.enable) {
1614 // Enable Pointer Capture.
1615 if (haveWindowWithPointerCapture &&
1616 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001617 // This can happen if pointer capture is disabled and re-enabled before we notify the
1618 // app of the state change, so there is no need to notify the app.
1619 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1620 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001621 }
1622 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001623 // This can happen if a window requests capture and immediately releases capture.
1624 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001625 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001626 return;
1627 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001628 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1629 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1630 return;
1631 }
1632
Vishnu Nairc519ff72021-01-21 08:23:08 -08001633 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001634 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1635 mWindowTokenWithPointerCapture = token;
1636 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001637 // Disable Pointer Capture.
1638 // We do not check if the sequence number matches for requests to disable Pointer Capture
1639 // for two reasons:
1640 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1641 // to disable capture with the same sequence number: one generated by
1642 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1643 // Capture being disabled in InputReader.
1644 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1645 // actual Pointer Capture state that affects events being generated by input devices is
1646 // in InputReader.
1647 if (!haveWindowWithPointerCapture) {
1648 // Pointer capture was already forcefully disabled because of focus change.
1649 dropReason = DropReason::NOT_DROPPED;
1650 return;
1651 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001652 token = mWindowTokenWithPointerCapture;
1653 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001654 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001655 setPointerCaptureLocked(false);
1656 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001657 }
1658
1659 auto channel = getInputChannelLocked(token);
1660 if (channel == nullptr) {
1661 // Window has gone away, clean up Pointer Capture state.
1662 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001663 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001664 setPointerCaptureLocked(false);
1665 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001666 return;
1667 }
1668 InputTarget target;
1669 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001670 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001671 entry->dispatchInProgress = true;
1672 dispatchEventLocked(currentTime, entry, {target});
1673
1674 dropReason = DropReason::NOT_DROPPED;
1675}
1676
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001677void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1678 const std::shared_ptr<TouchModeEntry>& entry) {
1679 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001680 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001681 if (windowHandles.empty()) {
1682 return;
1683 }
1684 const std::vector<InputTarget> inputTargets =
1685 getInputTargetsFromWindowHandlesLocked(windowHandles);
1686 if (inputTargets.empty()) {
1687 return;
1688 }
1689 entry->dispatchInProgress = true;
1690 dispatchEventLocked(currentTime, entry, inputTargets);
1691}
1692
1693std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1694 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1695 std::vector<InputTarget> inputTargets;
1696 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001697 const sp<IBinder>& token = handle->getToken();
1698 if (token == nullptr) {
1699 continue;
1700 }
1701 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1702 if (channel == nullptr) {
1703 continue; // Window has gone away
1704 }
1705 InputTarget target;
1706 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001707 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001708 inputTargets.push_back(target);
1709 }
1710 return inputTargets;
1711}
1712
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001713bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001714 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001716 if (!entry->dispatchInProgress) {
1717 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1718 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1719 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1720 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001721 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 // We have seen two identical key downs in a row which indicates that the device
1723 // driver is automatically generating key repeats itself. We take note of the
1724 // repeat here, but we disable our own next key repeat timer since it is clear that
1725 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001726 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1727 // Make sure we don't get key down from a different device. If a different
1728 // device Id has same key pressed down, the new device Id will replace the
1729 // current one to hold the key repeat with repeat count reset.
1730 // In the future when got a KEY_UP on the device id, drop it and do not
1731 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1733 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001734 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 } else {
1736 // Not a repeat. Save key down state in case we do see a repeat later.
1737 resetKeyRepeatLocked();
1738 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1739 }
1740 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001741 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1742 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001743 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001744 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001745 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1746 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001747 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 resetKeyRepeatLocked();
1749 }
1750
1751 if (entry->repeatCount == 1) {
1752 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1753 } else {
1754 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1755 }
1756
1757 entry->dispatchInProgress = true;
1758
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001759 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 }
1761
1762 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001763 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 if (currentTime < entry->interceptKeyWakeupTime) {
1765 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1766 *nextWakeupTime = entry->interceptKeyWakeupTime;
1767 }
1768 return false; // wait until next wakeup
1769 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001770 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 entry->interceptKeyWakeupTime = 0;
1772 }
1773
1774 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001775 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001777 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001778 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001779
1780 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1781 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1782 };
1783 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001784 // Poke user activity for keys not passed to user
1785 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 return false; // wait for the command to run
1787 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001788 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001790 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001791 if (*dropReason == DropReason::NOT_DROPPED) {
1792 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794 }
1795
1796 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001797 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001798 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1800 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001801 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001802 // Poke user activity for undispatched keys
1803 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 return true;
1805 }
1806
1807 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001808 InputEventInjectionResult injectionResult;
1809 sp<WindowInfoHandle> focusedWindow =
1810 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1811 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001812 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 return false;
1814 }
1815
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001816 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001817 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 return true;
1819 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001820 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1821
1822 std::vector<InputTarget> inputTargets;
1823 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001824 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001825 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001827 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829
1830 // Dispatch the key.
1831 dispatchEventLocked(currentTime, entry, inputTargets);
1832 return true;
1833}
1834
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001836 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1837 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1838 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1839 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1840 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1841 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1842 entry.metaState, entry.repeatCount, entry.downTime);
1843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844}
1845
Prabir Pradhancef936d2021-07-21 16:17:52 +00001846void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1847 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001848 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001849 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1850 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1851 "source=0x%x, sensorType=%s",
1852 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001853 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001854 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001855 auto command = [this, entry]() REQUIRES(mLock) {
1856 scoped_unlock unlock(mLock);
1857
1858 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001859 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001860 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001861 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1862 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001863 };
1864 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001865}
1866
1867bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001868 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1869 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001870 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 }
Chris Yef59a2f42020-10-16 12:55:26 -07001872 { // acquire lock
1873 std::scoped_lock _l(mLock);
1874
1875 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1876 std::shared_ptr<EventEntry> entry = *it;
1877 if (entry->type == EventEntry::Type::SENSOR) {
1878 it = mInboundQueue.erase(it);
1879 releaseInboundEventLocked(entry);
1880 }
1881 }
1882 }
1883 return true;
1884}
1885
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001886bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001887 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001888 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 entry->dispatchInProgress = true;
1892
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001893 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 }
1895
1896 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001897 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001898 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1900 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 return true;
1902 }
1903
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001904 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905
1906 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001907 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908
1909 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 if (isPointerEvent) {
1912 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001913
1914 if (mDragState &&
1915 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1916 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1917 pilferPointersLocked(mDragState->dragWindow->getToken());
1918 }
1919
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001920 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001921 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001922 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001923 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1924 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 } else {
1926 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001927 sp<WindowInfoHandle> focusedWindow =
1928 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1929 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1930 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1931 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001932 InputTarget::Flags::FOREGROUND |
1933 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001934 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 return false;
1939 }
1940
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001941 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001942 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001943 return true;
1944 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001946 CancelationOptions::Mode mode(
1947 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1948 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001949 CancelationOptions options(mode, "input event injection failed");
1950 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 return true;
1952 }
1953
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001954 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001955 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956
1957 // Dispatch the motion.
1958 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001959 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 synthesizeCancelationEventsForAllConnectionsLocked(options);
1962 }
1963 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
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002003 for (uint32_t i = 0; i < entry.pointerCount; 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 Vishniakou86587282019-09-09 18:20:15 +01002043 if (DEBUG_FOCUS) {
2044 ALOGD("Dropping event delivery to target with channel '%s' because it "
2045 "is no longer registered with the input dispatcher.",
2046 inputTarget.inputChannel->getName().c_str());
2047 }
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 Vishniakou4fe57392022-10-25 13:44:30 -07002262 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2263 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);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002287 bool switchedDevice = false;
2288 if (oldState != nullptr) {
2289 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2290 const bool anotherDeviceIsActive =
2291 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2292 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002293 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002294
2295 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2296 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2297 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002298 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2299 // touchable windows.
2300 const bool wasDown = oldState != nullptr && oldState->isDown();
2301 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2302 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002303 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2304 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2305 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002306 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002307
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002308 // If pointers are already down, let's finish the current gesture and ignore the new events
2309 // from another device. However, if the new event is a down event, let's cancel the current
2310 // touch and let the new one take over.
2311 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002312 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002313 << " is already down in display " << displayId << ": " << entry.getDescription();
2314 // TODO(b/211379801): test multiple simultaneous input streams.
2315 outInjectionResult = InputEventInjectionResult::FAILED;
2316 return {}; // wrong device
2317 }
2318
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002320 // If a new gesture is starting, clear the touch state completely.
2321 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002323 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002324 ALOGI("Dropping move event because a pointer for a different device is already active "
2325 "in display %" PRId32,
2326 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002327 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002328 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002329 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
2331
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002332 if (isHoverAction) {
2333 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2334 // all of the existing hovering pointers and recompute.
2335 tempTouchState.clearHoveringPointers();
2336 }
2337
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2339 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002340 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002341 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002342 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002343 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2344 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002345 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002346 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002348
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002349 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002350 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002353 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002354 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002356 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002357 }
2358
Prabir Pradhan5735a322022-04-11 17:23:34 +00002359 // Verify targeted injection.
2360 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2361 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002362 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002364 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002365 }
2366
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002367 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002368 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002369 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2370 // New window supports splitting, but we should never split mouse events.
2371 isSplit = !isFromMouse;
2372 } else if (isSplit) {
2373 // New window does not support splitting but we have already split events.
2374 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002375 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2376 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002377 newTouchedWindowHandle = nullptr;
2378 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379 } else {
2380 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002381 // be delivered to a new window which supports split touch. Pointers from a mouse device
2382 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002383 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002384 }
2385
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002386 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002387 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002389 // Process the foreground window first so that it is the first to receive the event.
2390 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 }
2392
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002393 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002394 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2395 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002396 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002397 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002398 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002399 }
2400
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002402 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002403 continue;
2404 }
2405
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002406 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2407 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002408 // The "windowHandle" is the target of this hovering pointer.
2409 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002410 }
2411
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002413 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002414
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002415 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2416 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002418 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002419
2420 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002421 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002422 }
2423 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002424 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002426 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002427 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002428
2429 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002430 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002431 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002432 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002433 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002434
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002435 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2436 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2437
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002438 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2439 // still add a window to the touch state. We should avoid doing that, but some of the
2440 // later checks ("at least one foreground window") rely on this in order to dispatch
2441 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002442 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002443 isDownOrPointerDown
2444 ? std::make_optional(entry.eventTime)
2445 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002446
2447 // If this is the pointer going down and the touched window has a wallpaper
2448 // then also add the touched wallpaper windows so they are locked in for the duration
2449 // of the touch gesture.
2450 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2451 // engine only supports touch events. We would need to add a mechanism similar
2452 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002453 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002454 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2455 windowHandle->getInfo()->inputConfig.test(
2456 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2457 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2458 if (wallpaper != nullptr) {
2459 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2460 InputTarget::Flags::WINDOW_IS_OBSCURED |
2461 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2462 InputTarget::Flags::DISPATCH_AS_IS;
2463 if (isSplit) {
2464 wallpaperFlags |= InputTarget::Flags::SPLIT;
2465 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002466 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2467 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002468 }
2469 }
2470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002472
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002473 // If a window is already pilfering some pointers, give it this new pointer as well and
2474 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2475 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002476 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002477 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2478 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002479 // This window is already pilfering some pointers, and this new pointer is also
2480 // going to it. Therefore, take over this pointer and don't give it to anyone
2481 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002482 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002483 }
2484 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002485
2486 // Restrict all pilfered pointers to the pilfering windows.
2487 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 } else {
2489 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2490
2491 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002492 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002493 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2494 "dropped the pointer down event in display "
2495 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002496 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002497 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 }
2499
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002500 // If the pointer is not currently hovering, then ignore the event.
2501 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2502 const int32_t pointerId = entry.pointerProperties[0].id;
2503 if (oldState == nullptr ||
2504 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2505 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2506 "display "
2507 << displayId << ": " << entry.getDescription();
2508 outInjectionResult = InputEventInjectionResult::FAILED;
2509 return {};
2510 }
2511 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2512 }
2513
arthurhung6d4bed92021-03-17 11:59:33 +08002514 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002515
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002517 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002518 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002519 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002520 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002521 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002522 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002523 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002524 sp<WindowInfoHandle> newTouchedWindowHandle =
2525 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002526
Prabir Pradhan5735a322022-04-11 17:23:34 +00002527 // Verify targeted injection.
2528 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2529 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002530 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002531 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002532 }
2533
Vishnu Nair062a8672021-09-03 16:07:44 -07002534 // Drop touch events if requested by input feature
2535 if (newTouchedWindowHandle != nullptr &&
2536 shouldDropInput(entry, newTouchedWindowHandle)) {
2537 newTouchedWindowHandle = nullptr;
2538 }
2539
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002540 if (newTouchedWindowHandle != nullptr &&
2541 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002542 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2543 oldTouchedWindowHandle->getName().c_str(),
2544 newTouchedWindowHandle->getName().c_str(), displayId);
2545
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002547 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002548 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002549 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002550
2551 const TouchedWindow& touchedWindow =
2552 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2553 addWindowTargetLocked(oldTouchedWindowHandle,
2554 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002555 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556
2557 // Make a slippery entrance into the new window.
2558 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002559 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 }
2561
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002562 ftl::Flags<InputTarget::Flags> targetFlags =
2563 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002564 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002565 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002568 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
2570 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002571 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002572 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002573 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 }
2575
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002576 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2577 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002578
2579 // Check if the wallpaper window should deliver the corresponding event.
2580 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002581 tempTouchState, entry.deviceId, pointerId, targets);
2582 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2583 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 }
2585 }
Arthur Hung96483742022-11-15 03:30:48 +00002586
2587 // Update the pointerIds for non-splittable when it received pointer down.
2588 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2589 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002590 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002591 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2592 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2593 // Ignore drag window for it should just track one pointer.
2594 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2595 continue;
2596 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002597 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2598 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2599 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002600 }
2601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
2603
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002604 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002605 {
2606 std::vector<TouchedWindow> hoveringWindows =
2607 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2608 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002609 std::optional<InputTarget> target =
2610 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002611 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002612 if (!target) {
2613 continue;
2614 }
2615 // Hardcode to single hovering pointer for now.
2616 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2617 pointerIds.set(entry.pointerProperties[0].id);
2618 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2619 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622
Prabir Pradhan5735a322022-04-11 17:23:34 +00002623 // Ensure that all touched windows are valid for injection.
2624 if (entry.injectionState != nullptr) {
2625 std::string errs;
2626 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002627 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2628 if (err) errs += "\n - " + *err;
2629 }
2630 if (!errs.empty()) {
2631 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002632 "%s:%s",
2633 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002634 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002635 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002636 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002637 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002638
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002639 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2640 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002642 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002643 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002644 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002645 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002646 for (InputTarget& target : targets) {
2647 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2648 sp<WindowInfoHandle> targetWindow =
2649 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2650 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2651 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654 }
2655 }
2656 }
2657
Harry Cuttsb166c002023-05-09 13:06:05 +00002658 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2659 // only want the system UI to handle these gestures.
2660 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2661 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2662 if (isTouchpadNavGesture) {
2663 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2664 }
2665
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002666 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002667 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002668 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2669 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002670 // Windows with hovering pointers are getting persisted inside TouchState.
2671 // Do not send this event to those windows.
2672 continue;
2673 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002674
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002675 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002676 touchedWindow.getTouchingPointers(entry.deviceId),
2677 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002678 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002679
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002680 // During targeted injection, only allow owned targets to receive events
2681 std::erase_if(targets, [&](const InputTarget& target) {
2682 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2683 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2684 if (err) {
2685 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2686 << ": " << (*err);
2687 return true;
2688 }
2689 return false;
2690 });
2691
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002692 if (targets.empty()) {
2693 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2694 outInjectionResult = InputEventInjectionResult::FAILED;
2695 return {};
2696 }
2697
2698 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2699 // window that is actually receiving the entire gesture.
2700 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2701 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2702 })) {
2703 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2704 << entry.getDescription();
2705 outInjectionResult = InputEventInjectionResult::FAILED;
2706 return {};
2707 }
2708
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002709 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002710 // Drop the outside or hover touch windows since we will not care about them
2711 // in the next iteration.
2712 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002715 if (switchedDevice) {
2716 if (DEBUG_FOCUS) {
2717 ALOGD("Conflicting pointer actions: Switched to a different device.");
2718 }
2719 *outConflictingPointerActions = true;
2720 }
2721
2722 if (isHoverAction) {
2723 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002724 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002725 ALOGD_IF(DEBUG_FOCUS,
2726 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002727 *outConflictingPointerActions = true;
2728 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002729 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2730 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002731 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002732 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002733 // All pointers up or canceled.
2734 tempTouchState.reset();
2735 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2736 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002737 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2738 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002739 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002740 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002741 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2742 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002743 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2744 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2745 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 }
2747
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002748 // Save changes unless the action was scroll in which case the temporary touch
2749 // state was only valid for this one action.
2750 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002751 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002752 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002753 mTouchStatesByDisplay[displayId] = tempTouchState;
2754 } else {
2755 mTouchStatesByDisplay.erase(displayId);
2756 }
2757 }
2758
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002759 if (tempTouchState.windows.empty()) {
2760 mTouchStatesByDisplay.erase(displayId);
2761 }
2762
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002763 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764}
2765
arthurhung6d4bed92021-03-17 11:59:33 +08002766void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002767 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2768 // have an explicit reason to support it.
2769 constexpr bool isStylus = false;
2770
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002771 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002772 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002773 if (dropWindow) {
2774 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002775 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002776 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002777 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002778 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002779 }
2780 mDragState.reset();
2781}
2782
2783void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002784 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002785 return;
2786 }
2787
arthurhung6d4bed92021-03-17 11:59:33 +08002788 if (!mDragState->isStartDrag) {
2789 mDragState->isStartDrag = true;
2790 mDragState->isStylusButtonDownAtStart =
2791 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2792 }
2793
Arthur Hung54745652022-04-20 07:17:41 +00002794 // Find the pointer index by id.
2795 int32_t pointerIndex = 0;
2796 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2797 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2798 if (pointerProperties.id == mDragState->pointerId) {
2799 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002800 }
Arthur Hung54745652022-04-20 07:17:41 +00002801 }
arthurhung6d4bed92021-03-17 11:59:33 +08002802
Arthur Hung54745652022-04-20 07:17:41 +00002803 if (uint32_t(pointerIndex) == entry.pointerCount) {
2804 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002805 }
2806
2807 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2808 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2809 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2810
2811 switch (maskedAction) {
2812 case AMOTION_EVENT_ACTION_MOVE: {
2813 // Handle the special case : stylus button no longer pressed.
2814 bool isStylusButtonDown =
2815 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2816 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2817 finishDragAndDrop(entry.displayId, x, y);
2818 return;
2819 }
2820
2821 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2822 // until we have an explicit reason to support it.
2823 constexpr bool isStylus = false;
2824
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002825 sp<WindowInfoHandle> hoverWindowHandle =
2826 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2827 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002828 // enqueue drag exit if needed.
2829 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2830 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2831 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002832 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002833 y);
2834 }
2835 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2836 }
2837 // enqueue drag location if needed.
2838 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002839 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002840 }
2841 break;
2842 }
2843
2844 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002845 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002846 break;
2847 }
2848 // The drag pointer is up.
2849 [[fallthrough]];
2850 case AMOTION_EVENT_ACTION_UP:
2851 finishDragAndDrop(entry.displayId, x, y);
2852 break;
2853 case AMOTION_EVENT_ACTION_CANCEL: {
2854 ALOGD("Receiving cancel when drag and drop.");
2855 sendDropWindowCommandLocked(nullptr, 0, 0);
2856 mDragState.reset();
2857 break;
2858 }
arthurhungb89ccb02020-12-30 16:19:01 +08002859 }
2860}
2861
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002862std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2863 const sp<android::gui::WindowInfoHandle>& windowHandle,
2864 ftl::Flags<InputTarget::Flags> targetFlags,
2865 std::optional<nsecs_t> firstDownTimeInTarget) const {
2866 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2867 if (inputChannel == nullptr) {
2868 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2869 return {};
2870 }
2871 InputTarget inputTarget;
2872 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002873 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002874 inputTarget.flags = targetFlags;
2875 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2876 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2877 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2878 if (displayInfoIt != mDisplayInfos.end()) {
2879 inputTarget.displayTransform = displayInfoIt->second.transform;
2880 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002881 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002882 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2883 }
2884 return inputTarget;
2885}
2886
chaviw98318de2021-05-19 16:45:23 -05002887void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002888 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002889 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002890 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002891 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002892 std::vector<InputTarget>::iterator it =
2893 std::find_if(inputTargets.begin(), inputTargets.end(),
2894 [&windowHandle](const InputTarget& inputTarget) {
2895 return inputTarget.inputChannel->getConnectionToken() ==
2896 windowHandle->getToken();
2897 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002898
chaviw98318de2021-05-19 16:45:23 -05002899 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002900
2901 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002902 std::optional<InputTarget> target =
2903 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2904 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002905 return;
2906 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002907 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002908 it = inputTargets.end() - 1;
2909 }
2910
2911 ALOG_ASSERT(it->flags == targetFlags);
2912 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2913
chaviw1ff3d1e2020-07-01 15:53:47 -07002914 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915}
2916
Michael Wright3dd60e22019-03-27 22:06:44 +00002917void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002918 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002919 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2920 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002921
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002922 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2923 InputTarget target;
2924 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002925 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002926 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2927 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002928 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2929 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002930 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002931 target.setDefaultPointerTransform(target.displayTransform);
2932 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
2934}
2935
Robert Carrc9bf1d32020-04-13 17:21:08 -07002936/**
2937 * Indicate whether one window handle should be considered as obscuring
2938 * another window handle. We only check a few preconditions. Actually
2939 * checking the bounds is left to the caller.
2940 */
chaviw98318de2021-05-19 16:45:23 -05002941static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2942 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002943 // Compare by token so cloned layers aren't counted
2944 if (haveSameToken(windowHandle, otherHandle)) {
2945 return false;
2946 }
2947 auto info = windowHandle->getInfo();
2948 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002949 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002950 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002951 } else if (otherInfo->alpha == 0 &&
2952 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002953 // Those act as if they were invisible, so we don't need to flag them.
2954 // We do want to potentially flag touchable windows even if they have 0
2955 // opacity, since they can consume touches and alter the effects of the
2956 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002957 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002958 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2959 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002960 } else if (info->ownerUid == otherInfo->ownerUid) {
2961 // If ownerUid is the same we don't generate occlusion events as there
2962 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002963 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002964 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002965 return false;
2966 } else if (otherInfo->displayId != info->displayId) {
2967 return false;
2968 }
2969 return true;
2970}
2971
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002972/**
2973 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2974 * untrusted, one should check:
2975 *
2976 * 1. If result.hasBlockingOcclusion is true.
2977 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2978 * BLOCK_UNTRUSTED.
2979 *
2980 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2981 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2982 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2983 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2984 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2985 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2986 *
2987 * If neither of those is true, then it means the touch can be allowed.
2988 */
2989InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002990 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2991 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002992 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002993 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002994 TouchOcclusionInfo info;
2995 info.hasBlockingOcclusion = false;
2996 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002997 info.obscuringUid = gui::Uid::INVALID;
2998 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002999 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003000 if (windowHandle == otherHandle) {
3001 break; // All future windows are below us. Exit early.
3002 }
chaviw98318de2021-05-19 16:45:23 -05003003 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003004 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3005 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003006 if (DEBUG_TOUCH_OCCLUSION) {
3007 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003008 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003009 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003010 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3011 // we perform the checks below to see if the touch can be propagated or not based on the
3012 // window's touch occlusion mode
3013 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3014 info.hasBlockingOcclusion = true;
3015 info.obscuringUid = otherInfo->ownerUid;
3016 info.obscuringPackage = otherInfo->packageName;
3017 break;
3018 }
3019 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003020 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003021 float opacity =
3022 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3023 // Given windows A and B:
3024 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3025 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3026 opacityByUid[uid] = opacity;
3027 if (opacity > info.obscuringOpacity) {
3028 info.obscuringOpacity = opacity;
3029 info.obscuringUid = uid;
3030 info.obscuringPackage = otherInfo->packageName;
3031 }
3032 }
3033 }
3034 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003035 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003036 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003037 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003038 return info;
3039}
3040
chaviw98318de2021-05-19 16:45:23 -05003041std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003042 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003043 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003044 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3045 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3046 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003047 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003048 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003049 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3050 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003051 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3052 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3053 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003054 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003055}
3056
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003057bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3058 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003059 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3060 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 return false;
3062 }
3063 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003064 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003065 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003066 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003067 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3068 return false;
3069 }
3070 return true;
3071}
3072
chaviw98318de2021-05-19 16:45:23 -05003073bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003076 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3077 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003078 if (windowHandle == otherHandle) {
3079 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 }
chaviw98318de2021-05-19 16:45:23 -05003081 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003082 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003083 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 return true;
3085 }
3086 }
3087 return false;
3088}
3089
chaviw98318de2021-05-19 16:45:23 -05003090bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003091 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003092 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3093 const WindowInfo* windowInfo = windowHandle->getInfo();
3094 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003095 if (windowHandle == otherHandle) {
3096 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003097 }
chaviw98318de2021-05-19 16:45:23 -05003098 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003099 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003100 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003101 return true;
3102 }
3103 }
3104 return false;
3105}
3106
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003107std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003108 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003109 if (applicationHandle != nullptr) {
3110 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003111 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 } else {
3113 return applicationHandle->getName();
3114 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003115 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003116 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003118 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 }
3120}
3121
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003123 if (!isUserActivityEvent(eventEntry)) {
3124 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003125 return;
3126 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003127 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003128 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003129 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003130 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003131 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003132 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003133 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 }
3135 }
3136
3137 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003138 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003139 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003140 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3141 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 return;
3143 }
Josep del Riob3981622023-04-18 15:49:45 +00003144 if (windowDisablingUserActivityInfo != nullptr) {
3145 if (DEBUG_DISPATCH_CYCLE) {
3146 ALOGD("Not poking user activity: disabled by window '%s'.",
3147 windowDisablingUserActivityInfo->name.c_str());
3148 }
3149 return;
3150 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003151 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 eventType = USER_ACTIVITY_EVENT_TOUCH;
3153 }
3154 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003156 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003157 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3158 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 return;
3160 }
Josep del Riob3981622023-04-18 15:49:45 +00003161 // If the key code is unknown, we don't consider it user activity
3162 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3163 return;
3164 }
3165 // Don't inhibit events that were intercepted or are not passed to
3166 // the apps, like system shortcuts
3167 if (windowDisablingUserActivityInfo != nullptr &&
3168 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3169 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3170 if (DEBUG_DISPATCH_CYCLE) {
3171 ALOGD("Not poking user activity: disabled by window '%s'.",
3172 windowDisablingUserActivityInfo->name.c_str());
3173 }
3174 return;
3175 }
3176
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 eventType = USER_ACTIVITY_EVENT_BUTTON;
3178 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003180 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003182 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003183 break;
3184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
3186
Prabir Pradhancef936d2021-07-21 16:17:52 +00003187 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3188 REQUIRES(mLock) {
3189 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003190 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003191 };
3192 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193}
3194
3195void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003196 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003197 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003198 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003199 ATRACE_NAME_IF(ATRACE_ENABLED(),
3200 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3201 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003202 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003203 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003204 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003205 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003206 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003207 inputTarget.getPointerInfoString().c_str());
3208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209
3210 // Skip this event if the connection status is not normal.
3211 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003212 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003213 if (DEBUG_DISPATCH_CYCLE) {
3214 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003215 connection->getInputChannelName().c_str(),
3216 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 return;
3219 }
3220
3221 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003223 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003224 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003225 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003227 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003228 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003229 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3230 logDispatchStateLocked();
3231 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3232 "target on connection "
3233 << connection->getInputChannelName() << " for "
3234 << originalMotionEntry.getDescription();
3235 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003237 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3238 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 if (!splitMotionEntry) {
3240 return; // split event was dropped
3241 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003242 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3243 std::string reason = std::string("reason=pointer cancel on split window");
3244 android_log_event_list(LOGTAG_INPUT_CANCEL)
3245 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3246 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003247 if (DEBUG_FOCUS) {
3248 ALOGD("channel '%s' ~ Split motion event.",
3249 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003250 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003251 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003252 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3253 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 return;
3255 }
3256 }
3257
3258 // Not splitting. Enqueue dispatch entries for the event as is.
3259 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3260}
3261
3262void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003263 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003264 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003265 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003266 ATRACE_NAME_IF(ATRACE_ENABLED(),
3267 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3268 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003269 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3270 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003271
hongzuo liu95785e22022-09-06 02:51:35 +00003272 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
3274 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003285 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003286 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
3288 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003289 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 startDispatchCycleLocked(currentTime, connection);
3291 }
3292}
3293
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003294void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003296 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3299 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 return;
3301 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003302
3303 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3304 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
3306 // This is a new event.
3307 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003308 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003309 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003311 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3312 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003316 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003317 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3319 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003320 LOG(WARNING) << "channel " << connection->getInputChannelName()
3321 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 return; // skip the inconsistent event
3323 }
3324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003327 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003328 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003329 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3330 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3331 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3332 static_cast<int32_t>(IdGenerator::Source::OTHER);
3333 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003342 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3344 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003345 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 }
3347 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003348 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3349 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003350 if (DEBUG_DISPATCH_CYCLE) {
3351 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3352 "enter event",
3353 connection->getInputChannelName().c_str());
3354 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003355 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3356 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003360 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3361 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3362 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003363 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3365 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003366 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3371 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003372 LOG(WARNING) << "channel " << connection->getInputChannelName()
3373 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 return; // skip the inconsistent event
3375 }
3376
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003377 dispatchEntry->resolvedEventId =
3378 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3379 ? mIdGenerator.nextId()
3380 : motionEntry.id;
3381 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3382 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3383 ") to MotionEvent(id=0x%" PRIx32 ").",
3384 motionEntry.id, dispatchEntry->resolvedEventId);
3385 ATRACE_NAME(message.c_str());
3386 }
3387
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003388 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3389 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3390 // Skip reporting pointer down outside focus to the policy.
3391 break;
3392 }
3393
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003394 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003395 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396
3397 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003399 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003400 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003401 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3402 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003403 break;
3404 }
Chris Yef59a2f42020-10-16 12:55:26 -07003405 case EventEntry::Type::SENSOR: {
3406 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3407 break;
3408 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003409 case EventEntry::Type::CONFIGURATION_CHANGED:
3410 case EventEntry::Type::DEVICE_RESET: {
3411 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003412 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003413 break;
3414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
3416
3417 // Remember that we are waiting for this dispatch to complete.
3418 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003419 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 }
3421
3422 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003423 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003424 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003425}
3426
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003427/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003428 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003429 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003430 * The first role is to log input interaction with windows, which helps determine what the user was
3431 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3432 * that user started interacting with launcher window, as well as any other window that received
3433 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3434 * when the set of tokens that received the event changes. It is not logged again as long as the
3435 * user is interacting with the same windows.
3436 *
3437 * The second role is to track input device activity for metrics collection. For each input event,
3438 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3439 * input_interaction logs, the device interaction is reported even when the set of interaction
3440 * tokens do not change.
3441 *
3442 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3443 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003444 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003445void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3446 const std::vector<InputTarget>& targets) {
3447 int32_t deviceId;
3448 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003449 // Skip ACTION_UP events, and all events other than keys and motions
3450 if (entry.type == EventEntry::Type::KEY) {
3451 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3452 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3453 return;
3454 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003455 deviceId = keyEntry.deviceId;
3456 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003457 } else if (entry.type == EventEntry::Type::MOTION) {
3458 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3459 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003460 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3461 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 return;
3463 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003464 deviceId = motionEntry.deviceId;
3465 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003466 } else {
3467 return; // Not a key or a motion
3468 }
3469
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003470 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003471 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003472 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003473 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003474 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 continue; // Skip windows that receive ACTION_OUTSIDE
3476 }
3477
3478 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003479 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003480 if (connection == nullptr) {
3481 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003482 }
3483 newConnectionTokens.insert(std::move(token));
3484 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003485 if (target.windowHandle) {
3486 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3487 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003488 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003489
3490 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3491 REQUIRES(mLock) {
3492 scoped_unlock unlock(mLock);
3493 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3494 };
3495 postCommandLocked(std::move(command));
3496
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003497 if (newConnectionTokens == mInteractionConnectionTokens) {
3498 return; // no change
3499 }
3500 mInteractionConnectionTokens = newConnectionTokens;
3501
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003503 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003504 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003505 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003506 std::string message = "Interaction with: " + targetList;
3507 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003508 message += "<none>";
3509 }
3510 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3511}
3512
chaviwfd6d3512019-03-25 13:23:49 -07003513void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003514 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003515 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003516 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3517 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003518 return;
3519 }
3520
Vishnu Nairc519ff72021-01-21 08:23:08 -08003521 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003522 if (focusedToken == token) {
3523 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003524 return;
3525 }
3526
Prabir Pradhancef936d2021-07-21 16:17:52 +00003527 auto command = [this, token]() REQUIRES(mLock) {
3528 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003529 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003530 };
3531 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532}
3533
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003534status_t InputDispatcher::publishMotionEvent(Connection& connection,
3535 DispatchEntry& dispatchEntry) const {
3536 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3537 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3538
3539 PointerCoords scaledCoords[MAX_POINTERS];
3540 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3541
3542 // Set the X and Y offset and X and Y scale depending on the input source.
3543 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003544 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003545 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3546 if (globalScaleFactor != 1.0f) {
3547 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3548 scaledCoords[i] = motionEntry.pointerCoords[i];
3549 // Don't apply window scale here since we don't want scale to affect raw
3550 // coordinates. The scale will be sent back to the client and applied
3551 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003552 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003553 }
3554 usingCoords = scaledCoords;
3555 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003556 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003557 // We don't want the dispatch target to know the coordinates
3558 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3559 scaledCoords[i].clear();
3560 }
3561 usingCoords = scaledCoords;
3562 }
3563
3564 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3565
3566 // Publish the motion event.
3567 return connection.inputPublisher
3568 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3569 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3570 std::move(hmac), dispatchEntry.resolvedAction,
3571 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3572 motionEntry.edgeFlags, motionEntry.metaState,
3573 motionEntry.buttonState, motionEntry.classification,
3574 dispatchEntry.transform, motionEntry.xPrecision,
3575 motionEntry.yPrecision, motionEntry.xCursorPosition,
3576 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3577 motionEntry.downTime, motionEntry.eventTime,
3578 motionEntry.pointerCount, motionEntry.pointerProperties,
3579 usingCoords);
3580}
3581
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003583 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003584 ATRACE_NAME_IF(ATRACE_ENABLED(),
3585 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3586 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003587 if (DEBUG_DISPATCH_CYCLE) {
3588 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3589 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003591 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003592 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003594 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003595 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596
3597 // Publish the event.
3598 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003599 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3600 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003601 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3603 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003604 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003605 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3606 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003609 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003610 status = connection->inputPublisher
3611 .publishKeyEvent(dispatchEntry->seq,
3612 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3613 keyEntry.source, keyEntry.displayId,
3614 std::move(hmac), dispatchEntry->resolvedAction,
3615 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3616 keyEntry.scanCode, keyEntry.metaState,
3617 keyEntry.repeatCount, keyEntry.downTime,
3618 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003622 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003623 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003624 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3625 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003626 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003627 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003628 break;
3629 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003630
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003631 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003633 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003634 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003635 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003636 break;
3637 }
3638
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003639 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3640 const TouchModeEntry& touchModeEntry =
3641 static_cast<const TouchModeEntry&>(eventEntry);
3642 status = connection->inputPublisher
3643 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3644 touchModeEntry.inTouchMode);
3645
3646 break;
3647 }
3648
Prabir Pradhan99987712020-11-10 18:43:05 -08003649 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3650 const auto& captureEntry =
3651 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3652 status = connection->inputPublisher
3653 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003654 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003655 break;
3656 }
3657
arthurhungb89ccb02020-12-30 16:19:01 +08003658 case EventEntry::Type::DRAG: {
3659 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3660 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3661 dragEntry.id, dragEntry.x,
3662 dragEntry.y,
3663 dragEntry.isExiting);
3664 break;
3665 }
3666
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003667 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003668 case EventEntry::Type::DEVICE_RESET:
3669 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003670 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003671 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003672 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675
3676 // Check the result.
3677 if (status) {
3678 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003679 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003681 "This is unexpected because the wait queue is empty, so the pipe "
3682 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003683 "event to it, status=%s(%d)",
3684 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3685 status);
Harry Cutts33476232023-01-30 19:57:29 +00003686 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 } else {
3688 // Pipe is full and we are waiting for the app to finish process some events
3689 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003690 if (DEBUG_DISPATCH_CYCLE) {
3691 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3692 "waiting for the application to catch up",
3693 connection->getInputChannelName().c_str());
3694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 }
3696 } else {
3697 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003698 "status=%s(%d)",
3699 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3700 status);
Harry Cutts33476232023-01-30 19:57:29 +00003701 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 }
3703 return;
3704 }
3705
3706 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003707 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3708 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3709 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003710 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003711 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003712 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003713 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003714 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716}
3717
chaviw09c8d2d2020-08-24 15:48:26 -07003718std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3719 size_t size;
3720 switch (event.type) {
3721 case VerifiedInputEvent::Type::KEY: {
3722 size = sizeof(VerifiedKeyEvent);
3723 break;
3724 }
3725 case VerifiedInputEvent::Type::MOTION: {
3726 size = sizeof(VerifiedMotionEvent);
3727 break;
3728 }
3729 }
3730 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3731 return mHmacKeyManager.sign(start, size);
3732}
3733
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003734const std::array<uint8_t, 32> InputDispatcher::getSignature(
3735 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003736 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003737 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003738 // Only sign events up and down events as the purely move events
3739 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003740 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003741 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003742
3743 VerifiedMotionEvent verifiedEvent =
3744 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3745 verifiedEvent.actionMasked = actionMasked;
3746 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3747 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003748}
3749
3750const std::array<uint8_t, 32> InputDispatcher::getSignature(
3751 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3752 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3753 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3754 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003755 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003756}
3757
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003759 const std::shared_ptr<Connection>& connection,
3760 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003761 if (DEBUG_DISPATCH_CYCLE) {
3762 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3763 connection->getInputChannelName().c_str(), seq, toString(handled));
3764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003766 if (connection->status == Connection::Status::BROKEN ||
3767 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 return;
3769 }
3770
3771 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003772 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3773 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3774 };
3775 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776}
3777
3778void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003779 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003781 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003782 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3783 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
3786 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003787 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003788 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003789 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003790 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791
3792 // The connection appears to be unrecoverably broken.
3793 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003794 if (connection->status == Connection::Status::NORMAL) {
3795 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
3797 if (notify) {
3798 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3800 connection->getInputChannelName().c_str());
3801
3802 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003803 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003804 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003805 };
3806 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808 }
3809}
3810
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003811void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003812 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003813 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003814 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816}
3817
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003818void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003820 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822}
3823
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003824int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3825 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003826 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003827 if (connection == nullptr) {
3828 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3829 connectionToken.get(), events);
3830 return 0; // remove the callback
3831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003833 bool notify;
3834 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3835 if (!(events & ALOOPER_EVENT_INPUT)) {
3836 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3837 "events=0x%x",
3838 connection->getInputChannelName().c_str(), events);
3839 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 }
3841
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003842 nsecs_t currentTime = now();
3843 bool gotOne = false;
3844 status_t status = OK;
3845 for (;;) {
3846 Result<InputPublisher::ConsumerResponse> result =
3847 connection->inputPublisher.receiveConsumerResponse();
3848 if (!result.ok()) {
3849 status = result.error().code();
3850 break;
3851 }
3852
3853 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3854 const InputPublisher::Finished& finish =
3855 std::get<InputPublisher::Finished>(*result);
3856 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3857 finish.consumeTime);
3858 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003859 if (shouldReportMetricsForConnection(*connection)) {
3860 const InputPublisher::Timeline& timeline =
3861 std::get<InputPublisher::Timeline>(*result);
3862 mLatencyTracker
3863 .trackGraphicsLatency(timeline.inputEventId,
3864 connection->inputChannel->getConnectionToken(),
3865 std::move(timeline.graphicsTimeline));
3866 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003867 }
3868 gotOne = true;
3869 }
3870 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003871 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003872 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 return 1;
3874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 }
3876
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003877 notify = status != DEAD_OBJECT || !connection->monitor;
3878 if (notify) {
3879 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3880 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3881 status);
3882 }
3883 } else {
3884 // Monitor channels are never explicitly unregistered.
3885 // We do it automatically when the remote endpoint is closed so don't warn about them.
3886 const bool stillHaveWindowHandle =
3887 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3888 notify = !connection->monitor && stillHaveWindowHandle;
3889 if (notify) {
3890 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3891 connection->getInputChannelName().c_str(), events);
3892 }
3893 }
3894
3895 // Remove the channel.
3896 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3897 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898}
3899
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003900void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003902 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003903 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 }
3905}
3906
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003907void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003908 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003909 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003910 for (const Monitor& monitor : monitors) {
3911 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003912 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003913 }
3914}
3915
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003917 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003918 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003919 if (connection == nullptr) {
3920 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003922
3923 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924}
3925
3926void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003927 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li5af92f92023-07-14 14:36:22 +08003928 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3929 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3930 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3931 LOG(INFO) << __func__
3932 << ": Canceling drag and drop because the pointers for the drag window are being "
3933 "canceled.";
3934 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3935 mDragState.reset();
3936 }
3937
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003938 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 return;
3940 }
3941
3942 nsecs_t currentTime = now();
3943
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003944 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003945 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003947 if (cancelationEvents.empty()) {
3948 return;
3949 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003950 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3951 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003952 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003953 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003954 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003955 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003956
Arthur Hungb3307ee2021-10-14 10:57:37 +00003957 std::string reason = std::string("reason=").append(options.reason);
3958 android_log_event_list(LOGTAG_INPUT_CANCEL)
3959 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3960
hongzuo liu95785e22022-09-06 02:51:35 +00003961 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003962 // The target to use if we don't find a window associated with the channel.
3963 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3964 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3965 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003966
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003967 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003969 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003970
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003971 switch (cancelationEventEntry->type) {
3972 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003973 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00003974 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
3975 ? std::make_optional(keyEntry.displayId)
3976 : std::nullopt;
3977 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
3978 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003979 /*pointerIds=*/{}, keyEntry.downTime, targets);
3980 } else {
3981 targets.emplace_back(fallbackTarget);
3982 }
3983 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003984 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003987 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00003988 const std::optional<int32_t> targetDisplay =
3989 motionEntry.displayId != ADISPLAY_ID_NONE
3990 ? std::make_optional(motionEntry.displayId)
3991 : std::nullopt;
3992 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003993 std::bitset<MAX_POINTER_ID + 1> pointerIds;
3994 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
3995 pointerIndex++) {
3996 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
3997 }
Prabir Pradhan16463382023-10-12 23:03:19 +00003998 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS, pointerIds,
3999 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004000 } else {
4001 targets.emplace_back(fallbackTarget);
4002 const auto it = mDisplayInfos.find(motionEntry.displayId);
4003 if (it != mDisplayInfos.end()) {
4004 targets.back().displayTransform = it->second.transform;
4005 targets.back().setDefaultPointerTransform(it->second.transform);
4006 }
4007 }
4008 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004009 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004011 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004012 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004013 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4014 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004015 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004016 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004017 break;
4018 }
4019 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004020 case EventEntry::Type::DEVICE_RESET:
4021 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004022 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004023 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004024 break;
4025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 }
4027
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004028 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4029 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004030 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004032
hongzuo liu95785e22022-09-06 02:51:35 +00004033 // If the outbound queue was previously empty, start the dispatch cycle going.
4034 if (wasEmpty && !connection->outboundQueue.empty()) {
4035 startDispatchCycleLocked(currentTime, connection);
4036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037}
4038
Svet Ganov5d3bc372020-01-26 23:11:07 -08004039void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004040 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004041 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004042 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043 return;
4044 }
4045
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004046 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004047 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004048
4049 if (downEvents.empty()) {
4050 return;
4051 }
4052
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004053 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4055 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004056 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004057
chaviw98318de2021-05-19 16:45:23 -05004058 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004059 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004060
hongzuo liu95785e22022-09-06 02:51:35 +00004061 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004062 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004063 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004064 switch (downEventEntry->type) {
4065 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004066 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4067 if (windowHandle != nullptr) {
4068 std::bitset<MAX_POINTER_ID + 1> pointerIds;
4069 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount;
4070 pointerIndex++) {
4071 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4072 }
4073 addWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4074 motionEntry.downTime, targets);
4075 } else {
4076 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4077 .flags = targetFlags});
4078 const auto it = mDisplayInfos.find(motionEntry.displayId);
4079 if (it != mDisplayInfos.end()) {
4080 targets.back().displayTransform = it->second.transform;
4081 targets.back().setDefaultPointerTransform(it->second.transform);
4082 }
4083 }
4084 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004085 break;
4086 }
4087
4088 case EventEntry::Type::KEY:
4089 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004090 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004092 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004093 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004094 case EventEntry::Type::SENSOR:
4095 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004096 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004097 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004098 break;
4099 }
4100 }
4101
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004102 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4103 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004104 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004105 }
4106
hongzuo liu95785e22022-09-06 02:51:35 +00004107 // If the outbound queue was previously empty, start the dispatch cycle going.
4108 if (wasEmpty && !connection->outboundQueue.empty()) {
4109 startDispatchCycleLocked(downTime, connection);
4110 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004111}
4112
Arthur Hungc539dbb2022-12-08 07:45:36 +00004113void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4114 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4115 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004116 std::shared_ptr<Connection> wallpaperConnection =
4117 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004118 if (wallpaperConnection != nullptr) {
4119 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4120 }
4121 }
4122}
4123
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004124std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004125 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4126 nsecs_t splitDownTime) {
4127 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
4129 uint32_t splitPointerIndexMap[MAX_POINTERS];
4130 PointerProperties splitPointerProperties[MAX_POINTERS];
4131 PointerCoords splitPointerCoords[MAX_POINTERS];
4132
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004133 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 uint32_t splitPointerCount = 0;
4135
4136 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004139 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004141 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004143 splitPointerProperties[splitPointerCount] = pointerProperties;
4144 splitPointerCoords[splitPointerCount] =
4145 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 splitPointerCount += 1;
4147 }
4148 }
4149
4150 if (splitPointerCount != pointerIds.count()) {
4151 // This is bad. We are missing some of the pointers that we expected to deliver.
4152 // Most likely this indicates that we received an ACTION_MOVE events that has
4153 // different pointer ids than we expected based on the previous ACTION_DOWN
4154 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4155 // in this way.
4156 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004157 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004158 "a broken sequence of pointer ids from the input device: %s",
4159 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004160 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 }
4162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004163 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4166 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004167 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004169 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004171 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 if (pointerIds.count() == 1) {
4173 // The first/last pointer went down/up.
4174 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004176 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4177 ? AMOTION_EVENT_ACTION_CANCEL
4178 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 } else {
4180 // A secondary pointer went down/up.
4181 uint32_t splitPointerIndex = 0;
4182 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4183 splitPointerIndex += 1;
4184 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185 action = maskedAction |
4186 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 }
4188 } else {
4189 // An unrelated pointer changed.
4190 action = AMOTION_EVENT_ACTION_MOVE;
4191 }
4192 }
4193
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004194 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4195 logDispatchStateLocked();
4196 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4197 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4198 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004199 }
4200
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004201 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004202 ATRACE_NAME_IF(ATRACE_ENABLED(),
4203 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4204 ").",
4205 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004206 std::unique_ptr<MotionEntry> splitMotionEntry =
4207 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4208 originalMotionEntry.deviceId, originalMotionEntry.source,
4209 originalMotionEntry.displayId,
4210 originalMotionEntry.policyFlags, action,
4211 originalMotionEntry.actionButton,
4212 originalMotionEntry.flags, originalMotionEntry.metaState,
4213 originalMotionEntry.buttonState,
4214 originalMotionEntry.classification,
4215 originalMotionEntry.edgeFlags,
4216 originalMotionEntry.xPrecision,
4217 originalMotionEntry.yPrecision,
4218 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004219 originalMotionEntry.yCursorPosition, splitDownTime,
4220 splitPointerCount, splitPointerProperties,
4221 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004223 if (originalMotionEntry.injectionState) {
4224 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 splitMotionEntry->injectionState->refCount += 1;
4226 }
4227
4228 return splitMotionEntry;
4229}
4230
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004231void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4232 std::scoped_lock _l(mLock);
4233 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4234}
4235
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004236void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004237 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004238 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Antonio Kantekf16f2832021-09-28 04:39:20 +00004241 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004243 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004246 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 } // release lock
4249
4250 if (needWake) {
4251 mLooper->wake();
4252 }
4253}
4254
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004255void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004256 ALOGD_IF(debugInboundEventDetails(),
4257 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4258 ", deviceId=%d, source=%s, displayId=%" PRId32
4259 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4260 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004261 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4262 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4263 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004264 Result<void> keyCheck = validateKeyEvent(args.action);
4265 if (!keyCheck.ok()) {
4266 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 return;
4268 }
4269
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004270 uint32_t policyFlags = args.policyFlags;
4271 int32_t flags = args.flags;
4272 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004273 // InputDispatcher tracks and generates key repeats on behalf of
4274 // whatever notifies it, so repeatCount should always be set to 0
4275 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4277 policyFlags |= POLICY_FLAG_VIRTUAL;
4278 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 if (policyFlags & POLICY_FLAG_FUNCTION) {
4281 metaState |= AMETA_FUNCTION_ON;
4282 }
4283
4284 policyFlags |= POLICY_FLAG_TRUSTED;
4285
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004286 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004288 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4289 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4290 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291
Michael Wright2b3c3302018-03-02 17:19:13 +00004292 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004293 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004294 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4295 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298
Antonio Kantekf16f2832021-09-28 04:39:20 +00004299 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 { // acquire lock
4301 mLock.lock();
4302
4303 if (shouldSendKeyToInputFilterLocked(args)) {
4304 mLock.unlock();
4305
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004306 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004307 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 return; // event was consumed by the filter
4309 }
4310
4311 mLock.lock();
4312 }
4313
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004314 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004315 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4316 args.displayId, policyFlags, args.action, flags, keyCode,
4317 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 mLock.unlock();
4321 } // release lock
4322
4323 if (needWake) {
4324 mLooper->wake();
4325 }
4326}
4327
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004328bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 return mInputFilterEnabled;
4330}
4331
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004332void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004333 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004334 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004335 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004336 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004337 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4338 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004339 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4340 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4341 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4342 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4343 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004344 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004345 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4346 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004347 i, args.pointerProperties[i].id,
4348 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4349 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4350 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4351 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4352 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4353 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4354 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4355 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4356 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4357 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004360
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004361 Result<void> motionCheck =
4362 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4363 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004364 if (!motionCheck.ok()) {
4365 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4366 return;
4367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004369 if (DEBUG_VERIFY_EVENTS) {
4370 auto [it, _] =
4371 mVerifiersByDisplay.try_emplace(args.displayId,
4372 StringPrintf("display %" PRId32, args.displayId));
4373 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004374 it->second.processMovement(args.deviceId, args.source, args.action,
4375 args.getPointerCount(), args.pointerProperties.data(),
4376 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004377 if (!result.ok()) {
4378 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4379 }
4380 }
4381
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004382 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004384
4385 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004386 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004387 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4388 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391
Antonio Kantekf16f2832021-09-28 04:39:20 +00004392 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 { // acquire lock
4394 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004395 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4396 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4397 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004398 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004399 if (touchStateIt != mTouchStatesByDisplay.end()) {
4400 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004401 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004402 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4403 }
4404 }
4405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406
4407 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004408 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004409 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004410 displayTransform = it->second.transform;
4411 }
4412
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 mLock.unlock();
4414
4415 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004416 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4417 args.action, args.actionButton, args.flags, args.edgeFlags,
4418 args.metaState, args.buttonState, args.classification,
4419 displayTransform, args.xPrecision, args.yPrecision,
4420 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004421 args.downTime, args.eventTime, args.getPointerCount(),
4422 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423
4424 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004425 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 return; // event was consumed by the filter
4427 }
4428
4429 mLock.lock();
4430 }
4431
4432 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004433 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004434 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4435 args.displayId, policyFlags, args.action,
4436 args.actionButton, args.flags, args.metaState,
4437 args.buttonState, args.classification, args.edgeFlags,
4438 args.xPrecision, args.yPrecision,
4439 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004440 args.downTime, args.getPointerCount(),
4441 args.pointerProperties.data(),
4442 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004444 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4445 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004446 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004447 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004448 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4449 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4450 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004451 }
4452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004453 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 mLock.unlock();
4455 } // release lock
4456
4457 if (needWake) {
4458 mLooper->wake();
4459 }
4460}
4461
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004463 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004464 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4465 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004466 args.id, args.eventTime, args.deviceId, args.source,
4467 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004468 }
Chris Yef59a2f42020-10-16 12:55:26 -07004469
Antonio Kantekf16f2832021-09-28 04:39:20 +00004470 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004471 { // acquire lock
4472 mLock.lock();
4473
4474 // Just enqueue a new sensor event.
4475 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004476 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4477 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4478 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004479
4480 needWake = enqueueInboundEventLocked(std::move(newEntry));
4481 mLock.unlock();
4482 } // release lock
4483
4484 if (needWake) {
4485 mLooper->wake();
4486 }
4487}
4488
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004489void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004490 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004491 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4492 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004493 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004494 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004495}
4496
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004498 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499}
4500
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004501void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004502 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004503 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4504 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004505 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004508 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004510 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511}
4512
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004513void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004514 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004515 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4516 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518
Antonio Kantekf16f2832021-09-28 04:39:20 +00004519 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004521 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004523 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004524 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004525 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004526
4527 for (auto& [_, verifier] : mVerifiersByDisplay) {
4528 verifier.resetDevice(args.deviceId);
4529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 } // release lock
4531
4532 if (needWake) {
4533 mLooper->wake();
4534 }
4535}
4536
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004537void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004538 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004539 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4540 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004541 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004542
Antonio Kantekf16f2832021-09-28 04:39:20 +00004543 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004544 { // acquire lock
4545 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004546 auto entry =
4547 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004548 needWake = enqueueInboundEventLocked(std::move(entry));
4549 } // release lock
4550
4551 if (needWake) {
4552 mLooper->wake();
4553 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004554}
4555
Prabir Pradhan5735a322022-04-11 17:23:34 +00004556InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004557 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004558 InputEventInjectionSync syncMode,
4559 std::chrono::milliseconds timeout,
4560 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004561 Result<void> eventValidation = validateInputEvent(*event);
4562 if (!eventValidation.ok()) {
4563 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4564 return InputEventInjectionResult::FAILED;
4565 }
4566
Prabir Pradhan65613802023-02-22 23:36:58 +00004567 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004568 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4569 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4570 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4571 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004572 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004573 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
Prabir Pradhan5735a322022-04-11 17:23:34 +00004575 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004577 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004578 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4579 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4580 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4581 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4582 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004583 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004584 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004585 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004586 }
4587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004588 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004590 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004591 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004592 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004593 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004594 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4595 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4596 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004597 int32_t keyCode = incomingKey.getKeyCode();
4598 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004599 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004600 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004601 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4602 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4603 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004605 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4606 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004607 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004608
4609 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4610 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004611 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4613 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4614 std::to_string(t.duration().count()).c_str());
4615 }
4616 }
4617
4618 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004619 std::unique_ptr<KeyEntry> injectedEntry =
4620 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004621 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004622 incomingKey.getDisplayId(), policyFlags, action,
4623 flags, keyCode, incomingKey.getScanCode(), metaState,
4624 incomingKey.getRepeatCount(),
4625 incomingKey.getDownTime());
4626 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004627 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 }
4629
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004630 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004631 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004632 const bool isPointerEvent =
4633 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4634 // If a pointer event has no displayId specified, inject it to the default display.
4635 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4636 ? ADISPLAY_ID_DEFAULT
4637 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004638 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004639
4640 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004641 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004642 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004643 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004644 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4645 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4646 std::to_string(t.duration().count()).c_str());
4647 }
4648 }
4649
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004650 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4651 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4652 }
4653
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004654 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004655 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4656 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004657 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004658 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4659 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004660 displayId, policyFlags, motionEvent.getAction(),
4661 motionEvent.getActionButton(), flags,
4662 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004663 motionEvent.getButtonState(),
4664 motionEvent.getClassification(),
4665 motionEvent.getEdgeFlags(),
4666 motionEvent.getXPrecision(),
4667 motionEvent.getYPrecision(),
4668 motionEvent.getRawXCursorPosition(),
4669 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004670 motionEvent.getDownTime(),
4671 motionEvent.getPointerCount(),
4672 motionEvent.getPointerProperties(),
4673 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004674 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004675 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004676 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004677 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004678 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004679 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004680 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4681 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004682 displayId, policyFlags,
4683 motionEvent.getAction(),
4684 motionEvent.getActionButton(), flags,
4685 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004686 motionEvent.getButtonState(),
4687 motionEvent.getClassification(),
4688 motionEvent.getEdgeFlags(),
4689 motionEvent.getXPrecision(),
4690 motionEvent.getYPrecision(),
4691 motionEvent.getRawXCursorPosition(),
4692 motionEvent.getRawYCursorPosition(),
4693 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004694 motionEvent.getPointerCount(),
4695 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004696 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004697 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4698 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004699 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700 }
4701 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004704 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004705 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004706 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 }
4708
Prabir Pradhan5735a322022-04-11 17:23:34 +00004709 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004710 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 injectionState->injectionIsAsync = true;
4712 }
4713
4714 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004715 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716
4717 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004718 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004719 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004720 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004721 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004722 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004723 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
4725
4726 mLock.unlock();
4727
4728 if (needWake) {
4729 mLooper->wake();
4730 }
4731
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004732 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004734 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004736 if (syncMode == InputEventInjectionSync::NONE) {
4737 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 } else {
4739 for (;;) {
4740 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 break;
4743 }
4744
4745 nsecs_t remainingTimeout = endTime - now();
4746 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004747 if (DEBUG_INJECTION) {
4748 ALOGD("injectInputEvent - Timed out waiting for injection result "
4749 "to become available.");
4750 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004751 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 break;
4753 }
4754
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004755 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
4757
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004758 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4759 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004761 if (DEBUG_INJECTION) {
4762 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4763 injectionState->pendingForegroundDispatches);
4764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 nsecs_t remainingTimeout = endTime - now();
4766 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004767 if (DEBUG_INJECTION) {
4768 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4769 "dispatches to finish.");
4770 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004771 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 break;
4773 }
4774
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004775 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 }
4777 }
4778 }
4779
4780 injectionState->release();
4781 } // release lock
4782
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004783 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004784 LOG(INFO) << "injectInputEvent - Finished with result "
4785 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787
4788 return injectionResult;
4789}
4790
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004791std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004792 std::array<uint8_t, 32> calculatedHmac;
4793 std::unique_ptr<VerifiedInputEvent> result;
4794 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004795 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004796 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4797 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4798 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004799 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004800 break;
4801 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004802 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004803 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4804 VerifiedMotionEvent verifiedMotionEvent =
4805 verifiedMotionEventFromMotionEvent(motionEvent);
4806 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004807 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004808 break;
4809 }
4810 default: {
4811 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4812 return nullptr;
4813 }
4814 }
4815 if (calculatedHmac == INVALID_HMAC) {
4816 return nullptr;
4817 }
tyiu1573a672023-02-21 22:38:32 +00004818 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004819 return nullptr;
4820 }
4821 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004822}
4823
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004824void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004825 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004826 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004828 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004829 LOG(INFO) << "Setting input event injection result to "
4830 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004833 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 // Log the outcome since the injector did not wait for the injection result.
4835 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004837 ALOGV("Asynchronous input event injection succeeded.");
4838 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004839 case InputEventInjectionResult::TARGET_MISMATCH:
4840 ALOGV("Asynchronous input event injection target mismatch.");
4841 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004842 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004843 ALOGW("Asynchronous input event injection failed.");
4844 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004845 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004846 ALOGW("Asynchronous input event injection timed out.");
4847 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004848 case InputEventInjectionResult::PENDING:
4849 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4850 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 }
4852 }
4853
4854 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004855 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 }
4857}
4858
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004859void InputDispatcher::transformMotionEntryForInjectionLocked(
4860 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004861 // Input injection works in the logical display coordinate space, but the input pipeline works
4862 // display space, so we need to transform the injected events accordingly.
4863 const auto it = mDisplayInfos.find(entry.displayId);
4864 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004865 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004866
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004867 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4868 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4869 const vec2 cursor =
4870 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4871 {entry.xCursorPosition, entry.yCursorPosition});
4872 entry.xCursorPosition = cursor.x;
4873 entry.yCursorPosition = cursor.y;
4874 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004875 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004876 entry.pointerCoords[i] =
4877 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4878 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004879 }
4880}
4881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004882void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4883 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 if (injectionState) {
4885 injectionState->pendingForegroundDispatches += 1;
4886 }
4887}
4888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004889void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4890 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 if (injectionState) {
4892 injectionState->pendingForegroundDispatches -= 1;
4893
4894 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004895 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 }
4897 }
4898}
4899
chaviw98318de2021-05-19 16:45:23 -05004900const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004901 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004902 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004903 auto it = mWindowHandlesByDisplay.find(displayId);
4904 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004905}
4906
chaviw98318de2021-05-19 16:45:23 -05004907sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004908 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004909 if (windowHandleToken == nullptr) {
4910 return nullptr;
4911 }
4912
Prabir Pradhan16463382023-10-12 23:03:19 +00004913 if (!displayId) {
4914 // Look through all displays.
4915 for (auto& it : mWindowHandlesByDisplay) {
4916 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4917 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4918 if (windowHandle->getToken() == windowHandleToken) {
4919 return windowHandle;
4920 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004923 return nullptr;
4924 }
4925
Prabir Pradhan16463382023-10-12 23:03:19 +00004926 // Only look through the requested display.
4927 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004928 if (windowHandle->getToken() == windowHandleToken) {
4929 return windowHandle;
4930 }
4931 }
4932 return nullptr;
4933}
4934
chaviw98318de2021-05-19 16:45:23 -05004935sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4936 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004937 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004938 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4939 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004940 if (handle->getId() == windowHandle->getId() &&
4941 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004942 if (windowHandle->getInfo()->displayId != it.first) {
4943 ALOGE("Found window %s in display %" PRId32
4944 ", but it should belong to display %" PRId32,
4945 windowHandle->getName().c_str(), it.first,
4946 windowHandle->getInfo()->displayId);
4947 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004948 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 }
4951 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004952 return nullptr;
4953}
4954
chaviw98318de2021-05-19 16:45:23 -05004955sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004956 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4957 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958}
4959
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004960ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4961 auto displayInfoIt = mDisplayInfos.find(displayId);
4962 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4963 : kIdentityTransform;
4964}
4965
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004966bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4967 const MotionEntry& motionEntry) const {
4968 const WindowInfo& info = *window->getInfo();
4969
4970 // Skip spy window targets that are not valid for targeted injection.
4971 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004972 return false;
4973 }
4974
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004975 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4976 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4977 return false;
4978 }
4979
4980 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4981 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4982 window->getName().c_str());
4983 return false;
4984 }
4985
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004986 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004987 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004988 ALOGW("Not sending touch to %s because there's no corresponding connection",
4989 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004990 return false;
4991 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004992
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004993 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004994 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004995 return false;
4996 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004997
4998 // Drop events that can't be trusted due to occlusion
4999 const auto [x, y] = resolveTouchedPosition(motionEntry);
5000 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5001 if (!isTouchTrustedLocked(occlusionInfo)) {
5002 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005003 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005004 for (const auto& log : occlusionInfo.debugInfo) {
5005 ALOGD("%s", log.c_str());
5006 }
5007 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005008 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5009 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005010 return false;
5011 }
5012
5013 // Drop touch events if requested by input feature
5014 if (shouldDropInput(motionEntry, window)) {
5015 return false;
5016 }
5017
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005018 return true;
5019}
5020
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005021std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5022 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005023 auto connectionIt = mConnectionsByToken.find(token);
5024 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005025 return nullptr;
5026 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005027 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005028}
5029
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005030void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005031 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5032 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005033 // Remove all handles on a display if there are no windows left.
5034 mWindowHandlesByDisplay.erase(displayId);
5035 return;
5036 }
5037
5038 // Since we compare the pointer of input window handles across window updates, we need
5039 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005040 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5041 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5042 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005043 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005044 }
5045
chaviw98318de2021-05-19 16:45:23 -05005046 std::vector<sp<WindowInfoHandle>> newHandles;
5047 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005048 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005049 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005050 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005051 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005052 const bool canReceiveInput =
5053 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5054 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005055 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005056 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005057 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005058 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005059 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005060 }
5061
5062 if (info->displayId != displayId) {
5063 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5064 handle->getName().c_str(), displayId, info->displayId);
5065 continue;
5066 }
5067
Robert Carredd13602020-04-13 17:24:34 -07005068 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5069 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005070 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005071 oldHandle->updateFrom(handle);
5072 newHandles.push_back(oldHandle);
5073 } else {
5074 newHandles.push_back(handle);
5075 }
5076 }
5077
5078 // Insert or replace
5079 mWindowHandlesByDisplay[displayId] = newHandles;
5080}
5081
Arthur Hungb92218b2018-08-14 12:00:21 +08005082/**
5083 * Called from InputManagerService, update window handle list by displayId that can receive input.
5084 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5085 * If set an empty list, remove all handles from the specific display.
5086 * For focused handle, check if need to change and send a cancel event to previous one.
5087 * For removed handle, check if need to send a cancel event if already in touch.
5088 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005089void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005090 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005091 if (DEBUG_FOCUS) {
5092 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005093 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005094 windowList += iwh->getName() + " ";
5095 }
5096 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098
Prabir Pradhand65552b2021-10-07 11:23:50 -07005099 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005100 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005101 const WindowInfo& info = *window->getInfo();
5102
5103 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005104 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005105 if (noInputWindow && window->getToken() != nullptr) {
5106 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5107 window->getName().c_str());
5108 window->releaseChannel();
5109 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005110
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005111 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005112 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5113 !info.inputConfig.test(
5114 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005115 "%s has feature SPY, but is not a trusted overlay.",
5116 window->getName().c_str());
5117
Prabir Pradhand65552b2021-10-07 11:23:50 -07005118 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005119 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5120 !info.inputConfig.test(
5121 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005122 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5123 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005124 }
5125
Arthur Hung72d8dc32020-03-28 00:48:39 +00005126 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005127 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128
chaviw98318de2021-05-19 16:45:23 -05005129 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005130
chaviw98318de2021-05-19 16:45:23 -05005131 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005132
Vishnu Nairc519ff72021-01-21 08:23:08 -08005133 std::optional<FocusResolver::FocusChanges> changes =
5134 mFocusResolver.setInputWindows(displayId, windowHandles);
5135 if (changes) {
5136 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005139 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5140 mTouchStatesByDisplay.find(displayId);
5141 if (stateIt != mTouchStatesByDisplay.end()) {
5142 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 for (size_t i = 0; i < state.windows.size();) {
5144 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005145 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005146 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147 ALOGD("Touched window was removed: %s in display %" PRId32,
5148 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005150 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5152 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005153 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005154 "touched window was removed");
5155 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005156 // Since we are about to drop the touch, cancel the events for the wallpaper as
5157 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005158 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005159 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5160 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005161 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005162 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005165 state.windows.erase(state.windows.begin() + i);
5166 } else {
5167 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 }
5169 }
arthurhungb89ccb02020-12-30 16:19:01 +08005170
arthurhung6d4bed92021-03-17 11:59:33 +08005171 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005172 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005173 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005174 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005175 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005176 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5177 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005178 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005179 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005180 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005181
Arthur Hung72d8dc32020-03-28 00:48:39 +00005182 // Release information for windows that are no longer present.
5183 // This ensures that unused input channels are released promptly.
5184 // Otherwise, they might stick around until the window handle is destroyed
5185 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005186 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005187 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005188 if (DEBUG_FOCUS) {
5189 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005190 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005191 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005192 }
chaviw291d88a2019-02-14 10:33:58 -08005193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194}
5195
5196void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005197 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005198 if (DEBUG_FOCUS) {
5199 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5200 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5201 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005202 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005203 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005204 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 } // release lock
5206
5207 // Wake up poll loop since it may need to make new input dispatching choices.
5208 mLooper->wake();
5209}
5210
Vishnu Nair599f1412021-06-21 10:39:58 -07005211void InputDispatcher::setFocusedApplicationLocked(
5212 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5213 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5214 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5215
5216 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5217 return; // This application is already focused. No need to wake up or change anything.
5218 }
5219
5220 // Set the new application handle.
5221 if (inputApplicationHandle != nullptr) {
5222 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5223 } else {
5224 mFocusedApplicationHandlesByDisplay.erase(displayId);
5225 }
5226
5227 // No matter what the old focused application was, stop waiting on it because it is
5228 // no longer focused.
5229 resetNoFocusedWindowTimeoutLocked();
5230}
5231
Tiger Huang721e26f2018-07-24 22:26:19 +08005232/**
5233 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5234 * the display not specified.
5235 *
5236 * We track any unreleased events for each window. If a window loses the ability to receive the
5237 * released event, we will send a cancel event to it. So when the focused display is changed, we
5238 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5239 * display. The display-specified events won't be affected.
5240 */
5241void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005242 if (DEBUG_FOCUS) {
5243 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5244 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005245 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005246 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005247
5248 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005249 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005250 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005251 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005252 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005253 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005254 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005255 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005256 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005258 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005259 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5260 }
5261 }
5262 mFocusedDisplayId = displayId;
5263
Chris Ye3c2d6f52020-08-09 10:39:48 -07005264 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005265 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005266 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005267
Vishnu Nairad321cd2020-08-20 16:40:21 -07005268 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005269 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005270 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005271 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005272 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005273 }
5274 }
5275 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005276 } // release lock
5277
5278 // Wake up poll loop since it may need to make new input dispatching choices.
5279 mLooper->wake();
5280}
5281
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005283 if (DEBUG_FOCUS) {
5284 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
5287 bool changed;
5288 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005289 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290
5291 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5292 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005293 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 }
5295
5296 if (mDispatchEnabled && !enabled) {
5297 resetAndDropEverythingLocked("dispatcher is being disabled");
5298 }
5299
5300 mDispatchEnabled = enabled;
5301 mDispatchFrozen = frozen;
5302 changed = true;
5303 } else {
5304 changed = false;
5305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306 } // release lock
5307
5308 if (changed) {
5309 // Wake up poll loop since it may need to make new input dispatching choices.
5310 mLooper->wake();
5311 }
5312}
5313
5314void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005315 if (DEBUG_FOCUS) {
5316 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318
5319 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005320 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321
5322 if (mInputFilterEnabled == enabled) {
5323 return;
5324 }
5325
5326 mInputFilterEnabled = enabled;
5327 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5328 } // release lock
5329
5330 // Wake up poll loop since there might be work to do to drop everything.
5331 mLooper->wake();
5332}
5333
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005334bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005335 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005336 bool needWake = false;
5337 {
5338 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005339 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005340 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005341 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005342 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5343 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005344 mTouchModePerDisplay.count(displayId) == 0
5345 ? "not set"
5346 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5347
Antonio Kantek15beb512022-06-13 22:35:41 +00005348 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5349 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005350 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005351 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005352 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005353 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5354 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005355 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005356 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005357 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005358 return false;
5359 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005360 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005361 mTouchModePerDisplay[displayId] = inTouchMode;
5362 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5363 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005364 needWake = enqueueInboundEventLocked(std::move(entry));
5365 } // release lock
5366
5367 if (needWake) {
5368 mLooper->wake();
5369 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005370 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005371}
5372
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005373bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005374 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5375 if (focusedToken == nullptr) {
5376 return false;
5377 }
5378 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5379 return isWindowOwnedBy(windowHandle, pid, uid);
5380}
5381
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005382bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005383 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5384 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5385 const sp<WindowInfoHandle> windowHandle =
5386 getWindowHandleLocked(connectionToken);
5387 return isWindowOwnedBy(windowHandle, pid, uid);
5388 }) != mInteractionConnectionTokens.end();
5389}
5390
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005391void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5392 if (opacity < 0 || opacity > 1) {
5393 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5394 return;
5395 }
5396
5397 std::scoped_lock lock(mLock);
5398 mMaximumObscuringOpacityForTouch = opacity;
5399}
5400
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005401std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5402InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005403 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5404 for (TouchedWindow& w : state.windows) {
5405 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005406 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005407 }
5408 }
5409 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005410 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005411}
5412
arthurhungb89ccb02020-12-30 16:19:01 +08005413bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5414 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005415 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005416 if (DEBUG_FOCUS) {
5417 ALOGD("Trivial transfer to same window.");
5418 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005419 return true;
5420 }
5421
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005423 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424
Arthur Hungabbb9d82021-09-01 14:52:30 +00005425 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005426 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005427
Arthur Hungabbb9d82021-09-01 14:52:30 +00005428 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005429 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 return false;
5431 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005432 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5433 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005434 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5435 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005436 return false;
5437 }
5438 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005439
Arthur Hungabbb9d82021-09-01 14:52:30 +00005440 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5441 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005442 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005443 return false;
5444 }
5445
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005446 if (DEBUG_FOCUS) {
5447 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005448 touchedWindow->windowHandle->getName().c_str(),
5449 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 }
5451
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005453 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005454 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005455 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005456 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457
Arthur Hungabbb9d82021-09-01 14:52:30 +00005458 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005459 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005460 ftl::Flags<InputTarget::Flags> newTargetFlags =
5461 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005462 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005463 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005464 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005465 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5466 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467
Arthur Hungabbb9d82021-09-01 14:52:30 +00005468 // Store the dragging window.
5469 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005470 if (pointerIds.count() != 1) {
5471 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5472 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005473 return false;
5474 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005475 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005476 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005477 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479
Arthur Hungabbb9d82021-09-01 14:52:30 +00005480 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005481 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5482 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005483 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005484 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005485 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5486 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005488 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5489 newTargetFlags);
5490
5491 // Check if the wallpaper window should deliver the corresponding event.
5492 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005493 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 } // release lock
5496
5497 // Wake up poll loop since it may need to make new input dispatching choices.
5498 mLooper->wake();
5499 return true;
5500}
5501
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005502/**
5503 * Get the touched foreground window on the given display.
5504 * Return null if there are no windows touched on that display, or if more than one foreground
5505 * window is being touched.
5506 */
5507sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5508 auto stateIt = mTouchStatesByDisplay.find(displayId);
5509 if (stateIt == mTouchStatesByDisplay.end()) {
5510 ALOGI("No touch state on display %" PRId32, displayId);
5511 return nullptr;
5512 }
5513
5514 const TouchState& state = stateIt->second;
5515 sp<WindowInfoHandle> touchedForegroundWindow;
5516 // If multiple foreground windows are touched, return nullptr
5517 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005518 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005519 if (touchedForegroundWindow != nullptr) {
5520 ALOGI("Two or more foreground windows: %s and %s",
5521 touchedForegroundWindow->getName().c_str(),
5522 window.windowHandle->getName().c_str());
5523 return nullptr;
5524 }
5525 touchedForegroundWindow = window.windowHandle;
5526 }
5527 }
5528 return touchedForegroundWindow;
5529}
5530
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005531// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005532bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005533 sp<IBinder> fromToken;
5534 { // acquire lock
5535 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005536 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005537 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005538 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5539 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005540 return false;
5541 }
5542
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005543 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5544 if (from == nullptr) {
5545 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5546 return false;
5547 }
5548
5549 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005550 } // release lock
5551
5552 return transferTouchFocus(fromToken, destChannelToken);
5553}
5554
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005556 if (DEBUG_FOCUS) {
5557 ALOGD("Resetting and dropping all events (%s).", reason);
5558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559
Michael Wrightfb04fd52022-11-24 22:31:11 +00005560 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561 synthesizeCancelationEventsForAllConnectionsLocked(options);
5562
5563 resetKeyRepeatLocked();
5564 releasePendingEventLocked();
5565 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005568 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005569 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570}
5571
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005572void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005573 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 dumpDispatchStateLocked(dump);
5575
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005576 std::istringstream stream(dump);
5577 std::string line;
5578
5579 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005580 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 }
5582}
5583
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005584std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005585 std::string dump;
5586
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005587 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5588 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005589
5590 std::string windowName = "None";
5591 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005592 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005593 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5594 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5595 : "token has capture without window";
5596 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005597 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005598
5599 return dump;
5600}
5601
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005602void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005603 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5604 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5605 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005606 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
Tiger Huang721e26f2018-07-24 22:26:19 +08005608 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5609 dump += StringPrintf(INDENT "FocusedApplications:\n");
5610 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5611 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005612 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005613 const std::chrono::duration timeout =
5614 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005615 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005616 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005617 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005620 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005622
Vishnu Nairc519ff72021-01-21 08:23:08 -08005623 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005624 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005626 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005627 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005628 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005629 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5630 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 }
5632 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005633 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 }
5635
arthurhung6d4bed92021-03-17 11:59:33 +08005636 if (mDragState) {
5637 dump += StringPrintf(INDENT "DragState:\n");
5638 mDragState->dump(dump, INDENT2);
5639 }
5640
Arthur Hungb92218b2018-08-14 12:00:21 +08005641 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005642 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5643 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5644 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5645 const auto& displayInfo = it->second;
5646 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5647 displayInfo.logicalHeight);
5648 displayInfo.transform.dump(dump, "transform", INDENT4);
5649 } else {
5650 dump += INDENT2 "No DisplayInfo found!\n";
5651 }
5652
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005653 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005654 dump += INDENT2 "Windows:\n";
5655 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005656 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5657 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005659 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005660 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005661 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005662 "applicationInfo.name=%s, "
5663 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005664 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005665 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005666 windowInfo->displayId,
5667 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005668 windowInfo->alpha, windowInfo->frame.left,
5669 windowInfo->frame.top, windowInfo->frame.right,
5670 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005671 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005672 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005673 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005674 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005675 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005676 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005677 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005678 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005679 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005680 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005681 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005682 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005683 }
5684 } else {
5685 dump += INDENT2 "Windows: <none>\n";
5686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 }
5688 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005689 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 }
5691
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005692 if (!mGlobalMonitorsByDisplay.empty()) {
5693 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5694 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005695 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005698 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 }
5700
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005701 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702
5703 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005704 if (!mRecentQueue.empty()) {
5705 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005706 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005707 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005708 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005709 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 }
5711 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005712 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 }
5714
5715 // Dump event currently being dispatched.
5716 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717 dump += INDENT "PendingEvent:\n";
5718 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005719 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005720 dump += StringPrintf(", age=%" PRId64 "ms\n",
5721 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005723 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724 }
5725
5726 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005727 if (!mInboundQueue.empty()) {
5728 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005729 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005730 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005731 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005732 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 }
5734 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005735 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 }
5737
Prabir Pradhancef936d2021-07-21 16:17:52 +00005738 if (!mCommandQueue.empty()) {
5739 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5740 } else {
5741 dump += INDENT "CommandQueue: <empty>\n";
5742 }
5743
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005744 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005745 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005746 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005747 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005748 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005749 connection->inputChannel->getFd().get(),
5750 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005751 connection->getWindowName().c_str(),
5752 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005755 if (!connection->outboundQueue.empty()) {
5756 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5757 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005758 dump += dumpQueue(connection->outboundQueue, currentTime);
5759
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005761 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005764 if (!connection->waitQueue.empty()) {
5765 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5766 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005767 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005769 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005771 std::stringstream inputStateDump;
5772 inputStateDump << connection->inputState;
5773 if (!isEmpty(inputStateDump)) {
5774 dump += INDENT3 "InputState: ";
5775 dump += inputStateDump.str() + "\n";
5776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 }
5778 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005779 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781
5782 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005783 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5784 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 }
5788
Antonio Kantek15beb512022-06-13 22:35:41 +00005789 if (!mTouchModePerDisplay.empty()) {
5790 dump += INDENT "TouchModePerDisplay:\n";
5791 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5792 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5793 std::to_string(touchMode).c_str());
5794 }
5795 } else {
5796 dump += INDENT "TouchModePerDisplay: <none>\n";
5797 }
5798
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005799 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005800 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5801 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5802 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005803 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005804 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805}
5806
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005807void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005808 const size_t numMonitors = monitors.size();
5809 for (size_t i = 0; i < numMonitors; i++) {
5810 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005811 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005812 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5813 dump += "\n";
5814 }
5815}
5816
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005817class LooperEventCallback : public LooperCallback {
5818public:
5819 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5820 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5821
5822private:
5823 std::function<int(int events)> mCallback;
5824};
5825
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005826Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005827 if (DEBUG_CHANNEL_CREATION) {
5828 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005831 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005832 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005833 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005834
5835 if (result) {
5836 return base::Error(result) << "Failed to open input channel pair with name " << name;
5837 }
5838
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005840 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005841 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005842 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005843 std::shared_ptr<Connection> connection =
5844 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5845 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005847 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5848 ALOGE("Created a new connection, but the token %p is already known", token.get());
5849 }
5850 mConnectionsByToken.emplace(token, connection);
5851
5852 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5853 this, std::placeholders::_1, token);
5854
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005855 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5856 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 } // release lock
5858
5859 // Wake the looper because some connections have changed.
5860 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005861 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862}
5863
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005864Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005865 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005866 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005867 std::shared_ptr<InputChannel> serverChannel;
5868 std::unique_ptr<InputChannel> clientChannel;
5869 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5870 if (result) {
5871 return base::Error(result) << "Failed to open input channel pair with name " << name;
5872 }
5873
Michael Wright3dd60e22019-03-27 22:06:44 +00005874 { // acquire lock
5875 std::scoped_lock _l(mLock);
5876
5877 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005878 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5879 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005880 }
5881
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005882 std::shared_ptr<Connection> connection =
5883 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005884 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005885 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005886
5887 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5888 ALOGE("Created a new connection, but the token %p is already known", token.get());
5889 }
5890 mConnectionsByToken.emplace(token, connection);
5891 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5892 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005893
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005894 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005895
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005896 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5897 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005898 }
Garfield Tan15601662020-09-22 15:32:38 -07005899
Michael Wright3dd60e22019-03-27 22:06:44 +00005900 // Wake the looper because some connections have changed.
5901 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005902 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005903}
5904
Garfield Tan15601662020-09-22 15:32:38 -07005905status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005907 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908
Harry Cutts33476232023-01-30 19:57:29 +00005909 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 if (status) {
5911 return status;
5912 }
5913 } // release lock
5914
5915 // Wake the poll loop because removing the connection may have changed the current
5916 // synchronization state.
5917 mLooper->wake();
5918 return OK;
5919}
5920
Garfield Tan15601662020-09-22 15:32:38 -07005921status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5922 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005923 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005924 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005925 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926 return BAD_VALUE;
5927 }
5928
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005929 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005930
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005932 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 }
5934
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005935 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936
5937 nsecs_t currentTime = now();
5938 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5939
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005940 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 return OK;
5942}
5943
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005944void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005945 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5946 auto& [displayId, monitors] = *it;
5947 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5948 return monitor.inputChannel->getConnectionToken() == connectionToken;
5949 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005950
Michael Wright3dd60e22019-03-27 22:06:44 +00005951 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005952 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005953 } else {
5954 ++it;
5955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 }
5957}
5958
Michael Wright3dd60e22019-03-27 22:06:44 +00005959status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005960 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005961 return pilferPointersLocked(token);
5962}
Michael Wright3dd60e22019-03-27 22:06:44 +00005963
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005964status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005965 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5966 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005967 LOG(WARNING)
5968 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005969 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005970 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005971
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005972 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005973 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005974 LOG(WARNING)
5975 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5976 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005977 return BAD_VALUE;
5978 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005979 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5980 if (deviceIds.size() != 1) {
5981 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5982 << " in window: " << windowPtr->dump();
5983 return BAD_VALUE;
5984 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005986 for (const DeviceId deviceId : deviceIds) {
5987 TouchState& state = *statePtr;
5988 TouchedWindow& window = *windowPtr;
5989 // Send cancel events to all the input channels we're stealing from.
5990 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5991 "input channel stole pointer stream");
5992 options.deviceId = deviceId;
5993 options.displayId = displayId;
5994 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5995 options.pointerIds = pointerIds;
5996 std::string canceledWindows;
5997 for (const TouchedWindow& w : state.windows) {
5998 const std::shared_ptr<InputChannel> channel =
5999 getInputChannelLocked(w.windowHandle->getToken());
6000 if (channel != nullptr && channel->getConnectionToken() != token) {
6001 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6002 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6003 canceledWindows += channel->getName();
6004 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006005 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006006 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6007 LOG(INFO) << "Channel " << requestingChannel->getName()
6008 << " is stealing input gesture for device " << deviceId << " from "
6009 << canceledWindows;
6010
6011 // Prevent the gesture from being sent to any other windows.
6012 // This only blocks relevant pointers to be sent to other windows
6013 window.addPilferingPointers(deviceId, pointerIds);
6014
6015 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006016 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006017 return OK;
6018}
6019
Prabir Pradhan99987712020-11-10 18:43:05 -08006020void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6021 { // acquire lock
6022 std::scoped_lock _l(mLock);
6023 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006024 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006025 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6026 windowHandle != nullptr ? windowHandle->getName().c_str()
6027 : "token without window");
6028 }
6029
Vishnu Nairc519ff72021-01-21 08:23:08 -08006030 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006031 if (focusedToken != windowToken) {
6032 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6033 enabled ? "enable" : "disable");
6034 return;
6035 }
6036
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006037 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006038 ALOGW("Ignoring request to %s Pointer Capture: "
6039 "window has %s requested pointer capture.",
6040 enabled ? "enable" : "disable", enabled ? "already" : "not");
6041 return;
6042 }
6043
Christine Franksb768bb42021-11-29 12:11:31 -08006044 if (enabled) {
6045 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6046 mIneligibleDisplaysForPointerCapture.end(),
6047 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6048 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6049 return;
6050 }
6051 }
6052
Prabir Pradhan99987712020-11-10 18:43:05 -08006053 setPointerCaptureLocked(enabled);
6054 } // release lock
6055
6056 // Wake the thread to process command entries.
6057 mLooper->wake();
6058}
6059
Christine Franksb768bb42021-11-29 12:11:31 -08006060void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6061 { // acquire lock
6062 std::scoped_lock _l(mLock);
6063 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6064 if (!isEligible) {
6065 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6066 }
6067 } // release lock
6068}
6069
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006070std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006071 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006072 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006073 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006075 }
6076 }
6077 }
6078 return std::nullopt;
6079}
6080
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006081std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6082 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006083 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006084 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006085 }
6086
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006087 for (const auto& [token, connection] : mConnectionsByToken) {
6088 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006089 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 }
6091 }
Robert Carr4e670e52018-08-15 13:26:12 -07006092
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006093 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094}
6095
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006096std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006097 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006098 if (connection == nullptr) {
6099 return "<nullptr>";
6100 }
6101 return connection->getInputChannelName();
6102}
6103
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006104void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006105 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006106 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006107}
6108
Prabir Pradhancef936d2021-07-21 16:17:52 +00006109void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006110 const std::shared_ptr<Connection>& connection,
6111 uint32_t seq, bool handled,
6112 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006113 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006114 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006115
6116 { // Start critical section
6117 auto dispatchEntryIt =
6118 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6119 [seq](auto& e) { return e->seq == seq; });
6120 if (dispatchEntryIt == connection->waitQueue.end()) {
6121 return;
6122 }
6123
6124 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6125
6126 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6127 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6128 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6129 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6130 }
6131 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6132 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6133 connection->inputChannel->getConnectionToken(),
6134 dispatchEntry.deliveryTime, consumeTime, finishTime);
6135 }
6136
6137 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6138 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6139 restartEvent =
6140 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6141 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6142 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6143 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6144 motionEntry, handled);
6145 } else {
6146 restartEvent = false;
6147 }
6148 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006149
6150 // Dequeue the event and start the next cycle.
6151 // Because the lock might have been released, it is possible that the
6152 // contents of the wait queue to have been drained, so we need to double-check
6153 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006154 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6155 [seq](auto& e) { return e->seq == seq; });
6156 if (entryIt != connection->waitQueue.end()) {
6157 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6158 connection->waitQueue.erase(entryIt);
6159
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6161 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6162 if (!connection->responsive) {
6163 connection->responsive = isConnectionResponsive(*connection);
6164 if (connection->responsive) {
6165 // The connection was unresponsive, and now it's responsive.
6166 processConnectionResponsiveLocked(*connection);
6167 }
6168 }
6169 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006170 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006171 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006172 traceOutboundQueueLength(*connection);
6173 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006174 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006175 }
6176 }
6177
6178 // Start the next dispatch cycle for this connection.
6179 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180}
6181
Prabir Pradhancef936d2021-07-21 16:17:52 +00006182void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6183 const sp<IBinder>& newToken) {
6184 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6185 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006186 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006187 };
6188 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189}
6190
Prabir Pradhancef936d2021-07-21 16:17:52 +00006191void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6192 auto command = [this, token, x, y]() REQUIRES(mLock) {
6193 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006194 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006195 };
6196 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006197}
6198
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006199void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006200 if (connection == nullptr) {
6201 LOG_ALWAYS_FATAL("Caller must check for nullness");
6202 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6204 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006205 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006206 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006207 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 return;
6209 }
6210 /**
6211 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6212 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6213 * has changed. This could cause newer entries to time out before the already dispatched
6214 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6215 * processes the events linearly. So providing information about the oldest entry seems to be
6216 * most useful.
6217 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006218 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6219 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006220 std::string reason =
6221 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006222 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006223 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006224 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006225 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006226 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006227
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006228 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6229
6230 // Stop waking up for events on this connection, it is already unresponsive
6231 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006232}
6233
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006234void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6235 std::string reason =
6236 StringPrintf("%s does not have a focused window", application->getName().c_str());
6237 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006238
Yabin Cui8eb9c552023-06-08 18:05:07 +00006239 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006240 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006241 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 };
6243 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006244}
6245
chaviw98318de2021-05-19 16:45:23 -05006246void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006247 const std::string& reason) {
6248 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6249 updateLastAnrStateLocked(windowLabel, reason);
6250}
6251
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006252void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6253 const std::string& reason) {
6254 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006255 updateLastAnrStateLocked(windowLabel, reason);
6256}
6257
6258void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6259 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006261 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 struct tm tm;
6263 localtime_r(&t, &tm);
6264 char timestr[64];
6265 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006266 mLastAnrState.clear();
6267 mLastAnrState += INDENT "ANR:\n";
6268 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006269 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6270 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006271 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272}
6273
Prabir Pradhancef936d2021-07-21 16:17:52 +00006274void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6275 KeyEntry& entry) {
6276 const KeyEvent event = createKeyEvent(entry);
6277 nsecs_t delay = 0;
6278 { // release lock
6279 scoped_unlock unlock(mLock);
6280 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006281 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6283 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6284 std::to_string(t.duration().count()).c_str());
6285 }
6286 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287
6288 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006289 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006290 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006291 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006293 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006294 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006296}
6297
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006299 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006300 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006301 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006303 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006304 };
6305 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006306}
6307
Prabir Pradhanedd96402022-02-15 01:46:16 -08006308void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006309 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006310 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006311 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006312 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006313 };
6314 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006315}
6316
6317/**
6318 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6319 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6320 * command entry to the command queue.
6321 */
6322void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6323 std::string reason) {
6324 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006325 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006326 if (connection.monitor) {
6327 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6328 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006329 pid = findMonitorPidByTokenLocked(connectionToken);
6330 } else {
6331 // The connection is a window
6332 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6333 reason.c_str());
6334 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6335 if (handle != nullptr) {
6336 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006337 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006339 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340}
6341
6342/**
6343 * Tell the policy that a connection has become responsive so that it can stop ANR.
6344 */
6345void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6346 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006347 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006349 pid = findMonitorPidByTokenLocked(connectionToken);
6350 } else {
6351 // The connection is a window
6352 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6353 if (handle != nullptr) {
6354 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006355 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006356 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006357 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006358}
6359
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006360bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006361 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006362 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006363 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006364 if (!handled) {
6365 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006366 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006367 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006368 return false;
6369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006371 // Get the fallback key state.
6372 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006373 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006374 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006375 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006376 connection->inputState.removeFallbackKey(originalKeyCode);
6377 }
6378
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006379 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006380 // If the application handles the original key for which we previously
6381 // generated a fallback or if the window is not a foreground window,
6382 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006383 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006384 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006385 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6386 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6387 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6388 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6389 keyEntry.policyFlags);
6390 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006391 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006392 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393
6394 mLock.unlock();
6395
Prabir Pradhana41d2442023-04-20 21:30:40 +00006396 if (const auto unhandledKeyFallback =
6397 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6398 event, keyEntry.policyFlags);
6399 unhandledKeyFallback) {
6400 event = *unhandledKeyFallback;
6401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402
6403 mLock.lock();
6404
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006405 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006406 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006407 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 "application handled the original non-fallback key "
6409 "or is no longer a foreground target, "
6410 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006411 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006413 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 connection->inputState.removeFallbackKey(originalKeyCode);
6415 }
6416 } else {
6417 // If the application did not handle a non-fallback key, first check
6418 // that we are in a good state to perform unhandled key event processing
6419 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006420 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006421 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006422 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6423 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6424 "since this is not an initial down. "
6425 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6426 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6427 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006428 return false;
6429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006431 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006432 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6433 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6434 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6435 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6436 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006437 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438
6439 mLock.unlock();
6440
Prabir Pradhana41d2442023-04-20 21:30:40 +00006441 bool fallback = false;
6442 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6443 event, keyEntry.policyFlags);
6444 fb) {
6445 fallback = true;
6446 event = *fb;
6447 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006448
6449 mLock.lock();
6450
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006451 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 connection->inputState.removeFallbackKey(originalKeyCode);
6453 return false;
6454 }
6455
6456 // Latch the fallback keycode for this key on an initial down.
6457 // The fallback keycode cannot change at any other point in the lifecycle.
6458 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006460 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006462 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006464 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006465 }
6466
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006467 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468
6469 // Cancel the fallback key if the policy decides not to send it anymore.
6470 // We will continue to dispatch the key to the policy but we will no
6471 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006472 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6473 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6475 if (fallback) {
6476 ALOGD("Unhandled key event: Policy requested to send key %d"
6477 "as a fallback for %d, but on the DOWN it had requested "
6478 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006479 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006480 } else {
6481 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6482 "but on the DOWN it had requested to send %d. "
6483 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006484 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006485 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487
Michael Wrightfb04fd52022-11-24 22:31:11 +00006488 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006490 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491 synthesizeCancelationEventsForConnectionLocked(connection, options);
6492
6493 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006495 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006496 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006497 }
6498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006500 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6501 {
6502 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006503 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006504 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006505 for (const auto& [key, value] : fallbackKeys) {
6506 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 }
6508 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6509 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006510 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006511 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512
6513 if (fallback) {
6514 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006515 keyEntry.eventTime = event.getEventTime();
6516 keyEntry.deviceId = event.getDeviceId();
6517 keyEntry.source = event.getSource();
6518 keyEntry.displayId = event.getDisplayId();
6519 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006520 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006521 keyEntry.scanCode = event.getScanCode();
6522 keyEntry.metaState = event.getMetaState();
6523 keyEntry.repeatCount = event.getRepeatCount();
6524 keyEntry.downTime = event.getDownTime();
6525 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006526
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6528 ALOGD("Unhandled key event: Dispatching fallback key. "
6529 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006530 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006531 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006532 return true; // restart the event
6533 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006534 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6535 ALOGD("Unhandled key event: No fallback key.");
6536 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006537
6538 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006539 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540 }
6541 }
6542 return false;
6543}
6544
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006545bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006546 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006547 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 return false;
6549}
6550
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551void InputDispatcher::traceInboundQueueLengthLocked() {
6552 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006553 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 }
6555}
6556
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006557void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 if (ATRACE_ENABLED()) {
6559 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006560 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6561 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 }
6563}
6564
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006565void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566 if (ATRACE_ENABLED()) {
6567 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006568 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6569 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570 }
6571}
6572
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006573void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006574 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006576 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577 dumpDispatchStateLocked(dump);
6578
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006579 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006580 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006581 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582 }
6583}
6584
6585void InputDispatcher::monitor() {
6586 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006587 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006589 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590}
6591
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006592/**
6593 * Wake up the dispatcher and wait until it processes all events and commands.
6594 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6595 * this method can be safely called from any thread, as long as you've ensured that
6596 * the work you are interested in completing has already been queued.
6597 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006598bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006599 /**
6600 * Timeout should represent the longest possible time that a device might spend processing
6601 * events and commands.
6602 */
6603 constexpr std::chrono::duration TIMEOUT = 100ms;
6604 std::unique_lock lock(mLock);
6605 mLooper->wake();
6606 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6607 return result == std::cv_status::no_timeout;
6608}
6609
Vishnu Naire798b472020-07-23 13:52:21 -07006610/**
6611 * Sets focus to the window identified by the token. This must be called
6612 * after updating any input window handles.
6613 *
6614 * Params:
6615 * request.token - input channel token used to identify the window that should gain focus.
6616 * request.focusedToken - the token that the caller expects currently to be focused. If the
6617 * specified token does not match the currently focused window, this request will be dropped.
6618 * If the specified focused token matches the currently focused window, the call will succeed.
6619 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6620 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6621 * when requesting the focus change. This determines which request gets
6622 * precedence if there is a focus change request from another source such as pointer down.
6623 */
Vishnu Nair958da932020-08-21 17:12:37 -07006624void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6625 { // acquire lock
6626 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006627 std::optional<FocusResolver::FocusChanges> changes =
6628 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6629 if (changes) {
6630 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006631 }
6632 } // release lock
6633 // Wake up poll loop since it may need to make new input dispatching choices.
6634 mLooper->wake();
6635}
6636
Vishnu Nairc519ff72021-01-21 08:23:08 -08006637void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6638 if (changes.oldFocus) {
6639 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006640 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006641 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006642 "focus left window");
6643 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006644 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006645 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006646 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006647 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006648 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006649 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006650 }
6651
Prabir Pradhan99987712020-11-10 18:43:05 -08006652 // If a window has pointer capture, then it must have focus. We need to ensure that this
6653 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6654 // If the window loses focus before it loses pointer capture, then the window can be in a state
6655 // where it has pointer capture but not focus, violating the contract. Therefore we must
6656 // dispatch the pointer capture event before the focus event. Since focus events are added to
6657 // the front of the queue (above), we add the pointer capture event to the front of the queue
6658 // after the focus events are added. This ensures the pointer capture event ends up at the
6659 // front.
6660 disablePointerCaptureForcedLocked();
6661
Vishnu Nairc519ff72021-01-21 08:23:08 -08006662 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006663 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006664 }
6665}
Vishnu Nair958da932020-08-21 17:12:37 -07006666
Prabir Pradhan99987712020-11-10 18:43:05 -08006667void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006668 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006669 return;
6670 }
6671
6672 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6673
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006674 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006675 setPointerCaptureLocked(false);
6676 }
6677
6678 if (!mWindowTokenWithPointerCapture) {
6679 // No need to send capture changes because no window has capture.
6680 return;
6681 }
6682
6683 if (mPendingEvent != nullptr) {
6684 // Move the pending event to the front of the queue. This will give the chance
6685 // for the pending event to be dropped if it is a captured event.
6686 mInboundQueue.push_front(mPendingEvent);
6687 mPendingEvent = nullptr;
6688 }
6689
6690 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006691 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006692 mInboundQueue.push_front(std::move(entry));
6693}
6694
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006695void InputDispatcher::setPointerCaptureLocked(bool enable) {
6696 mCurrentPointerCaptureRequest.enable = enable;
6697 mCurrentPointerCaptureRequest.seq++;
6698 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006699 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006700 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006701 };
6702 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006703}
6704
Vishnu Nair599f1412021-06-21 10:39:58 -07006705void InputDispatcher::displayRemoved(int32_t displayId) {
6706 { // acquire lock
6707 std::scoped_lock _l(mLock);
6708 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006709 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006710 setFocusedApplicationLocked(displayId, nullptr);
6711 // Call focus resolver to clean up stale requests. This must be called after input windows
6712 // have been removed for the removed display.
6713 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006714 // Reset pointer capture eligibility, regardless of previous state.
6715 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006716 // Remove the associated touch mode state.
6717 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006718 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006719 } // release lock
6720
6721 // Wake up poll loop since it may need to make new input dispatching choices.
6722 mLooper->wake();
6723}
6724
Patrick Williamsd828f302023-04-28 17:52:08 -05006725void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006726 // The listener sends the windows as a flattened array. Separate the windows by display for
6727 // more convenient parsing.
6728 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006729 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006730 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006731 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006732 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006733
6734 { // acquire lock
6735 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006736
6737 // Ensure that we have an entry created for all existing displays so that if a displayId has
6738 // no windows, we can tell that the windows were removed from the display.
6739 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6740 handlesPerDisplay[displayId];
6741 }
6742
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006743 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006744 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006745 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6746 }
6747
6748 for (const auto& [displayId, handles] : handlesPerDisplay) {
6749 setInputWindowsLocked(handles, displayId);
6750 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006751
6752 if (update.vsyncId < mWindowInfosVsyncId) {
6753 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6754 ", current update vsync id: %" PRId64,
6755 mWindowInfosVsyncId, update.vsyncId);
6756 }
6757 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006758 }
6759 // Wake up poll loop since it may need to make new input dispatching choices.
6760 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006761}
6762
Vishnu Nair062a8672021-09-03 16:07:44 -07006763bool InputDispatcher::shouldDropInput(
6764 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006765 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6766 (windowHandle->getInfo()->inputConfig.test(
6767 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006768 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006769 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6770 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006771 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006772 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006773 windowHandle->getInfo()->displayId);
6774 return true;
6775 }
6776 return false;
6777}
6778
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006779void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006780 const gui::WindowInfosUpdate& update) {
6781 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006782}
6783
Arthur Hungdfd528e2021-12-08 13:23:04 +00006784void InputDispatcher::cancelCurrentTouch() {
6785 {
6786 std::scoped_lock _l(mLock);
6787 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006788 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006789 "cancel current touch");
6790 synthesizeCancelationEventsForAllConnectionsLocked(options);
6791
6792 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006793 }
6794 // Wake up poll loop since there might be work to do.
6795 mLooper->wake();
6796}
6797
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006798void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6799 std::scoped_lock _l(mLock);
6800 mMonitorDispatchingTimeout = timeout;
6801}
6802
Arthur Hungc539dbb2022-12-08 07:45:36 +00006803void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6804 const sp<WindowInfoHandle>& oldWindowHandle,
6805 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006806 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006807 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006808 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6809 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006810 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6811 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6812 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6813 newWindowHandle->getInfo()->inputConfig.test(
6814 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6815 const sp<WindowInfoHandle> oldWallpaper =
6816 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6817 const sp<WindowInfoHandle> newWallpaper =
6818 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6819 if (oldWallpaper == newWallpaper) {
6820 return;
6821 }
6822
6823 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006824 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6825 addWindowTargetLocked(oldWallpaper,
6826 oldTouchedWindow.targetFlags |
6827 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006828 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6829 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006830 }
6831
6832 if (newWallpaper != nullptr) {
6833 state.addOrUpdateWindow(newWallpaper,
6834 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6835 InputTarget::Flags::WINDOW_IS_OBSCURED |
6836 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006837 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006838 }
6839}
6840
6841void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6842 ftl::Flags<InputTarget::Flags> newTargetFlags,
6843 const sp<WindowInfoHandle> fromWindowHandle,
6844 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006845 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006846 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006847 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6848 fromWindowHandle->getInfo()->inputConfig.test(
6849 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6850 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6851 toWindowHandle->getInfo()->inputConfig.test(
6852 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6853
6854 const sp<WindowInfoHandle> oldWallpaper =
6855 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6856 const sp<WindowInfoHandle> newWallpaper =
6857 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6858 if (oldWallpaper == newWallpaper) {
6859 return;
6860 }
6861
6862 if (oldWallpaper != nullptr) {
6863 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6864 "transferring touch focus to another window");
6865 state.removeWindowByToken(oldWallpaper->getToken());
6866 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6867 }
6868
6869 if (newWallpaper != nullptr) {
6870 nsecs_t downTimeInTarget = now();
6871 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6872 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6873 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6874 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006875 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6876 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006877 std::shared_ptr<Connection> wallpaperConnection =
6878 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006879 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006880 std::shared_ptr<Connection> toConnection =
6881 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006882 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6883 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6884 wallpaperFlags);
6885 }
6886 }
6887}
6888
6889sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6890 const sp<WindowInfoHandle>& windowHandle) const {
6891 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6892 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6893 bool foundWindow = false;
6894 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6895 if (!foundWindow && otherHandle != windowHandle) {
6896 continue;
6897 }
6898 if (windowHandle == otherHandle) {
6899 foundWindow = true;
6900 continue;
6901 }
6902
6903 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6904 return otherHandle;
6905 }
6906 }
6907 return nullptr;
6908}
6909
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006910void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6911 std::scoped_lock _l(mLock);
6912
6913 mConfig.keyRepeatTimeout = timeout;
6914 mConfig.keyRepeatDelay = delay;
6915}
6916
Garfield Tane84e6f92019-08-29 17:28:41 -07006917} // namespace android::inputdispatcher