blob: 991d3e6efcc43e7bc5a958f642fa19911afb7a46 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056#define INDENT " "
57#define INDENT2 " "
58#define INDENT3 " "
59#define INDENT4 " "
60
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080061using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070062using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080063using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000064using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070066using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050067using android::gui::FocusRequest;
68using android::gui::TouchOcclusionMode;
69using android::gui::WindowInfo;
70using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080071using android::os::InputEventInjectionResult;
72using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000073namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080074
Garfield Tane84e6f92019-08-29 17:28:41 -070075namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Prabir Pradhancef936d2021-07-21 16:17:52 +000077namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000078// Temporarily releases a held mutex for the lifetime of the instance.
79// Named to match std::scoped_lock
80class scoped_unlock {
81public:
82 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
83 ~scoped_unlock() { mMutex.lock(); }
84
85private:
86 std::mutex& mMutex;
87};
88
Michael Wrightd02c5b62014-02-10 15:10:22 -080089// Default input dispatching timeout if there is no focused application or paused window
90// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080091const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
92 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
93 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800100const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000103constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
104
105// Log a warning when an interception call takes longer than this to process.
106constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700108// Additional key latency in case a connection is still processing some motion events.
109// This will help with the case when a user touched a button that opens a new window,
110// and gives us the chance to dispatch the key to this new window.
111constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
112
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000114constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
115
Antonio Kantekea47acb2021-12-23 12:41:25 -0800116// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000117constexpr int LOGTAG_INPUT_INTERACTION = 62000;
118constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000119constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000120
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000121const ui::Transform kIdentityTransform;
122
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000123inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124 return systemTime(SYSTEM_TIME_MONOTONIC);
125}
126
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700127bool isEmpty(const std::stringstream& ss) {
128 return ss.rdbuf()->in_avail() == 0;
129}
130
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700131inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000132 if (binder == nullptr) {
133 return "<null>";
134 }
135 return StringPrintf("%p", binder.get());
136}
137
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000138static std::string uidString(const gui::Uid& uid) {
139 return uid.toString();
140}
141
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> validateKeyEvent(int32_t action) {
153 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154}
155
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700156Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800157 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_UP: {
160 if (pointerCount != 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_HOVER_ENTER:
167 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
169 if (pointerCount < 1) {
170 return Error() << "invalid pointer count " << pointerCount;
171 }
172 return {};
173 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800174 case AMOTION_EVENT_ACTION_CANCEL:
175 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800180 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700181 if (index < 0) {
182 return Error() << "invalid index " << index << " for "
183 << MotionEvent::actionToString(action);
184 }
185 if (index >= pointerCount) {
186 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
187 }
188 if (pointerCount <= 1) {
189 return Error() << "invalid pointer count " << pointerCount << " for "
190 << MotionEvent::actionToString(action);
191 }
192 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 }
194 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700195 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
196 if (actionButton == 0) {
197 return Error() << "action button should be nonzero for "
198 << MotionEvent::actionToString(action);
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700203 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500208 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
209}
210
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700211Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
212 const PointerProperties* pointerProperties) {
213 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
214 if (!actionCheck.ok()) {
215 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 return Error() << "Motion event has invalid pointer count " << pointerCount
219 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800221 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 for (size_t i = 0; i < pointerCount; i++) {
223 int32_t id = pointerProperties[i].id;
224 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer id " << id
226 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800231 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700233 return {};
234}
235
236Result<void> validateInputEvent(const InputEvent& event) {
237 switch (event.getType()) {
238 case InputEventType::KEY: {
239 const KeyEvent& key = static_cast<const KeyEvent&>(event);
240 const int32_t action = key.getAction();
241 return validateKeyEvent(action);
242 }
243 case InputEventType::MOTION: {
244 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
245 const int32_t action = motion.getAction();
246 const size_t pointerCount = motion.getPointerCount();
247 const PointerProperties* pointerProperties = motion.getPointerProperties();
248 const int32_t actionButton = motion.getActionButton();
249 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
250 }
251 default: {
252 return {};
253 }
254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255}
256
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000257std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000259 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 }
261
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000262 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 bool first = true;
264 Region::const_iterator cur = region.begin();
265 Region::const_iterator const tail = region.end();
266 while (cur != tail) {
267 if (first) {
268 first = false;
269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800272 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 cur++;
274 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000275 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276}
277
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000278std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
279 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500280 constexpr size_t maxEntries = 50; // max events to print
281 constexpr size_t skipBegin = maxEntries / 2;
282 const size_t skipEnd = queue.size() - maxEntries / 2;
283 // skip from maxEntries / 2 ... size() - maxEntries/2
284 // only print from 0 .. skipBegin and then from skipEnd .. size()
285
286 std::string dump;
287 for (size_t i = 0; i < queue.size(); i++) {
288 const DispatchEntry& entry = *queue[i];
289 if (i >= skipBegin && i < skipEnd) {
290 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
291 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
292 continue;
293 }
294 dump.append(INDENT4);
295 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800296 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
297 "ms",
298 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500299 ns2ms(currentTime - entry.eventEntry->eventTime));
300 if (entry.deliveryTime != 0) {
301 // This entry was delivered, so add information on how long we've been waiting
302 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
303 }
304 dump.append("\n");
305 }
306 return dump;
307}
308
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700309/**
310 * Find the entry in std::unordered_map by key, and return it.
311 * If the entry is not found, return a default constructed entry.
312 *
313 * Useful when the entries are vectors, since an empty vector will be returned
314 * if the entry is not found.
315 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
316 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700317template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700319 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700320 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800321}
322
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000323bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700324 if (first == second) {
325 return true;
326 }
327
328 if (first == nullptr || second == nullptr) {
329 return false;
330 }
331
332 return first->getToken() == second->getToken();
333}
334
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000335bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000336 if (first == nullptr || second == nullptr) {
337 return false;
338 }
339 return first->applicationInfo.token != nullptr &&
340 first->applicationInfo.token == second->applicationInfo.token;
341}
342
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800343template <typename T>
344size_t firstMarkedBit(T set) {
345 // TODO: replace with std::countr_zero from <bit> when that's available
346 LOG_ALWAYS_FATAL_IF(set.none());
347 size_t i = 0;
348 while (!set.test(i)) {
349 i++;
350 }
351 return i;
352}
353
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800354std::unique_ptr<DispatchEntry> createDispatchEntry(
355 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
356 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 if (inputTarget.useDefaultPointerTransform()) {
358 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700359 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700360 inputTarget.displayTransform,
361 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000362 }
363
364 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
365 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700368 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000369
370 // Use the first pointer information to normalize all other pointers. This could be any pointer
371 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 // uses the transform for the normalized pointer.
373 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800374 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376
377 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700378 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
380 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700381 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382
383 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700384 // First, apply the current pointer's transform to update the coordinates into
385 // window space.
386 pointerCoords[pointerIndex].transform(currTransform);
387 // Next, apply the inverse transform of the normalized coordinates so the
388 // current coordinates are transformed into the normalized coordinate space.
389 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 }
391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700392 std::unique_ptr<MotionEntry> combinedMotionEntry =
393 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
394 motionEntry.deviceId, motionEntry.source,
395 motionEntry.displayId, motionEntry.policyFlags,
396 motionEntry.action, motionEntry.actionButton,
397 motionEntry.flags, motionEntry.metaState,
398 motionEntry.buttonState, motionEntry.classification,
399 motionEntry.edgeFlags, motionEntry.xPrecision,
400 motionEntry.yPrecision, motionEntry.xCursorPosition,
401 motionEntry.yCursorPosition, motionEntry.downTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700402 motionEntry.pointerProperties, pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
404 if (motionEntry.injectionState) {
405 combinedMotionEntry->injectionState = motionEntry.injectionState;
406 combinedMotionEntry->injectionState->refCount += 1;
407 }
408
409 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700410 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700411 firstPointerTransform, inputTarget.displayTransform,
412 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000413 return dispatchEntry;
414}
415
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000416status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
417 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700418 std::unique_ptr<InputChannel> uniqueServerChannel;
419 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
420
421 serverChannel = std::move(uniqueServerChannel);
422 return result;
423}
424
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500425template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000426bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500427 if (lhs == nullptr && rhs == nullptr) {
428 return true;
429 }
430 if (lhs == nullptr || rhs == nullptr) {
431 return false;
432 }
433 return *lhs == *rhs;
434}
435
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000437 KeyEvent event;
438 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
439 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
440 entry.repeatCount, entry.downTime, entry.eventTime);
441 return event;
442}
443
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000444bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000445 // Do not keep track of gesture monitors. They receive every event and would disproportionately
446 // affect the statistics.
447 if (connection.monitor) {
448 return false;
449 }
450 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
451 if (!connection.responsive) {
452 return false;
453 }
454 return true;
455}
456
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000457bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000458 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
459 const int32_t& inputEventId = eventEntry.id;
460 if (inputEventId != dispatchEntry.resolvedEventId) {
461 // Event was transmuted
462 return false;
463 }
464 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
465 return false;
466 }
467 // Only track latency for events that originated from hardware
468 if (eventEntry.isSynthesized()) {
469 return false;
470 }
471 const EventEntry::Type& inputEventEntryType = eventEntry.type;
472 if (inputEventEntryType == EventEntry::Type::KEY) {
473 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
474 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
475 return false;
476 }
477 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
478 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
479 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
480 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
481 return false;
482 }
483 } else {
484 // Not a key or a motion
485 return false;
486 }
487 if (!shouldReportMetricsForConnection(connection)) {
488 return false;
489 }
490 return true;
491}
492
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493/**
494 * Connection is responsive if it has no events in the waitQueue that are older than the
495 * current time.
496 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000497bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000499 for (const auto& dispatchEntry : connection.waitQueue) {
500 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000501 return false;
502 }
503 }
504 return true;
505}
506
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507// Returns true if the event type passed as argument represents a user activity.
508bool isUserActivityEvent(const EventEntry& eventEntry) {
509 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000510 case EventEntry::Type::CONFIGURATION_CHANGED:
511 case EventEntry::Type::DEVICE_RESET:
512 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::FOCUS:
514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::KEY:
519 case EventEntry::Type::MOTION:
520 return true;
521 }
522}
523
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000525bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800527 const auto inputConfig = windowInfo.inputConfig;
528 if (windowInfo.displayId != displayId ||
529 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700532 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800534 return false;
535 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000536
537 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
538 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
539 // the window. Points on the right and bottom edges should not be inside the window, so we need
540 // to be careful about performing a hit test when the display is rotated, since the "right" and
541 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
542 // logical display in which WM determined the bounds. Perform the hit test in the logical
543 // display space to ensure these edges are considered correctly in all orientations.
544 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
545 const auto p = displayTransform.transform(x, y);
546 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800547 return false;
548 }
549 return true;
550}
551
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
553 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000554 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700555}
556
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
559// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
560// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800561// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000562bool canReceiveForegroundTouches(const WindowInfo& info) {
563 // A non-touchable window can still receive touch events (e.g. in the case of
564 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
565 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
566}
567
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000568bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700569 if (windowHandle == nullptr) {
570 return false;
571 }
572 const WindowInfo* windowInfo = windowHandle->getInfo();
573 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
574 return true;
575 }
576 return false;
577}
578
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579// Checks targeted injection using the window's owner's uid.
580// Returns an empty string if an entry can be sent to the given window, or an error message if the
581// entry is a targeted injection whose uid target doesn't match the window owner.
582std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
583 const EventEntry& entry) {
584 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
585 // The event was not injected, or the injected event does not target a window.
586 return {};
587 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000588 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("No valid window target for injection into uid %s.",
591 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000592 }
593 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
595 "owned by uid %s.",
596 uid.toString().c_str(), window->getName().c_str(),
597 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 return {};
600}
601
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
604 // Always dispatch mouse events to cursor position.
605 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607 }
608
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700609 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000610 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
611 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612}
613
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700614std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
615 if (eventEntry.type == EventEntry::Type::KEY) {
616 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
617 return keyEntry.downTime;
618 } else if (eventEntry.type == EventEntry::Type::MOTION) {
619 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
620 return motionEntry.downTime;
621 }
622 return std::nullopt;
623}
624
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000625/**
626 * Compare the old touch state to the new touch state, and generate the corresponding touched
627 * windows (== input targets).
628 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
629 * If the pointer just entered the new window, produce HOVER_ENTER.
630 * For pointers remaining in the window, produce HOVER_MOVE.
631 */
632std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
633 const TouchState& newTouchState,
634 const MotionEntry& entry) {
635 std::vector<TouchedWindow> out;
636 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700637
638 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
639 // ACTION_SCROLL events should not affect the hovering pointer dispatch
640 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000641 }
642
643 // We should consider all hovering pointers here. But for now, just use the first one
644 const int32_t pointerId = entry.pointerProperties[0].id;
645
646 std::set<sp<WindowInfoHandle>> oldWindows;
647 if (oldState != nullptr) {
648 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
649 }
650
651 std::set<sp<WindowInfoHandle>> newWindows =
652 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
653
654 // If the pointer is no longer in the new window set, send HOVER_EXIT.
655 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
656 if (newWindows.find(oldWindow) == newWindows.end()) {
657 TouchedWindow touchedWindow;
658 touchedWindow.windowHandle = oldWindow;
659 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 out.push_back(touchedWindow);
661 }
662 }
663
664 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
665 TouchedWindow touchedWindow;
666 touchedWindow.windowHandle = newWindow;
667 if (oldWindows.find(newWindow) == oldWindows.end()) {
668 // Any windows that have this pointer now, and didn't have it before, should get
669 // HOVER_ENTER
670 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
671 } else {
672 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700674 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000675 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
676 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700677 // The Accessibility injected touch exploration event stream
678 // has known inconsistencies, so log ERROR instead of
679 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700680 severity = android::base::LogSeverity::ERROR;
681 }
682 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700683 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
685 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700686 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000687 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
688 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
689 }
690 out.push_back(touchedWindow);
691 }
692 return out;
693}
694
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800695template <typename T>
696std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
697 left.insert(left.end(), right.begin(), right.end());
698 return left;
699}
700
Harry Cuttsb166c002023-05-09 13:06:05 +0000701// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
702// both.
703void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
704 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
705 if (!window.windowHandle->getInfo()->inputConfig.test(
706 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
707 // In addition to TouchState, erase this window from the input targets! We don't have a
708 // good way to do this today except by adding a nested loop.
709 // TODO(b/282025641): simplify this code once InputTargets are being identified
710 // separately from TouchedWindows.
711 std::erase_if(targets, [&](const InputTarget& target) {
712 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
713 });
714 return true;
715 }
716 return false;
717 });
718}
719
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700720/**
721 * In general, touch should be always split between windows. Some exceptions:
722 * 1. Don't split touch if all of the below is true:
723 * (a) we have an active pointer down *and*
724 * (b) a new pointer is going down that's from the same device *and*
725 * (c) the window that's receiving the current pointer does not support split touch.
726 * 2. Don't split mouse events
727 */
728bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
729 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
730 // We should never split mouse events
731 return false;
732 }
733 for (const TouchedWindow& touchedWindow : touchState.windows) {
734 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
735 // Spy windows should not affect whether or not touch is split.
736 continue;
737 }
738 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
739 continue;
740 }
741 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
742 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
743 // Wallpaper window should not affect whether or not touch is split
744 continue;
745 }
746
747 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
748 return false;
749 }
750 }
751 return true;
752}
753
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000754} // namespace
755
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756// --- InputDispatcher ---
757
Prabir Pradhana41d2442023-04-20 21:30:40 +0000758InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800759 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
760
Prabir Pradhana41d2442023-04-20 21:30:40 +0000761InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800762 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700763 : mPolicy(policy),
764 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700765 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800766 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700768 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800770 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700771 mDispatchEnabled(false),
772 mDispatchFrozen(false),
773 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100774 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000775 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800776 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800777 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000778 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000779 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700780 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800781 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700783 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700784#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700785 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700786#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700787 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788}
789
790InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792
Prabir Pradhancef936d2021-07-21 16:17:52 +0000793 resetKeyRepeatLocked();
794 releasePendingEventLocked();
795 drainInboundQueueLocked();
796 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000798 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700799 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000800 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802}
803
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700805 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700806 return ALREADY_EXISTS;
807 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700808 mThread = std::make_unique<InputThread>(
809 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
810 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700811}
812
813status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700814 if (mThread && mThread->isCallingThread()) {
815 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700816 return INVALID_OPERATION;
817 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700818 mThread.reset();
819 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700820}
821
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700823 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800825 std::scoped_lock _l(mLock);
826 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827
828 // Run a dispatch loop if there are no pending commands.
829 // The dispatch loop might enqueue commands to run afterwards.
830 if (!haveCommandsLocked()) {
831 dispatchOnceInnerLocked(&nextWakeupTime);
832 }
833
834 // Run all pending commands if there are any.
835 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000836 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700837 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800839
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 // If we are still waiting for ack on some events,
841 // we might have to wake up earlier to check if an app is anr'ing.
842 const nsecs_t nextAnrCheck = processAnrsLocked();
843 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
844
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800845 // We are about to enter an infinitely long sleep, because we have no commands or
846 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700847 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800848 mDispatcherEnteredIdle.notify_all();
849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 } // release lock
851
852 // Wait for callback or timeout or wake. (make sure we round up, not down)
853 nsecs_t currentTime = now();
854 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
855 mLooper->pollOnce(timeoutMillis);
856}
857
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500859 * Raise ANR if there is no focused window.
860 * Before the ANR is raised, do a final state check:
861 * 1. The currently focused application must be the same one we are waiting for.
862 * 2. Ensure we still don't have a focused window.
863 */
864void InputDispatcher::processNoFocusedWindowAnrLocked() {
865 // Check if the application that we are waiting for is still focused.
866 std::shared_ptr<InputApplicationHandle> focusedApplication =
867 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
868 if (focusedApplication == nullptr ||
869 focusedApplication->getApplicationToken() !=
870 mAwaitedFocusedApplication->getApplicationToken()) {
871 // Unexpected because we should have reset the ANR timer when focused application changed
872 ALOGE("Waited for a focused window, but focused application has already changed to %s",
873 focusedApplication->getName().c_str());
874 return; // The focused application has changed.
875 }
876
chaviw98318de2021-05-19 16:45:23 -0500877 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500878 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
879 if (focusedWindowHandle != nullptr) {
880 return; // We now have a focused window. No need for ANR.
881 }
882 onAnrLocked(mAwaitedFocusedApplication);
883}
884
885/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 * Check if any of the connections' wait queues have events that are too old.
887 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
888 * Return the time at which we should wake up next.
889 */
890nsecs_t InputDispatcher::processAnrsLocked() {
891 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700892 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
894 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
895 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500896 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700897 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500898 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700899 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700900 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500901 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700902 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
903 }
904 }
905
906 // Check if any connection ANRs are due
907 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
908 if (currentTime < nextAnrCheck) { // most likely scenario
909 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
910 }
911
912 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700913 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 if (connection == nullptr) {
915 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
916 return nextAnrCheck;
917 }
918 connection->responsive = false;
919 // Stop waking up for this unresponsive connection
920 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000921 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700922 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923}
924
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800925std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700926 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800927 if (connection->monitor) {
928 return mMonitorDispatchingTimeout;
929 }
930 const sp<WindowInfoHandle> window =
931 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500933 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500935 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936}
937
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
939 nsecs_t currentTime = now();
940
Jeff Browndc5992e2014-04-11 01:27:26 -0700941 // Reset the key repeat timer whenever normal dispatch is suspended while the
942 // device is in a non-interactive state. This is to ensure that we abort a key
943 // repeat if the device is just coming out of sleep.
944 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 resetKeyRepeatLocked();
946 }
947
948 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
949 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100950 if (DEBUG_FOCUS) {
951 ALOGD("Dispatch frozen. Waiting some more.");
952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 return;
954 }
955
956 // Optimize latency of app switches.
957 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
958 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
959 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
960 if (mAppSwitchDueTime < *nextWakeupTime) {
961 *nextWakeupTime = mAppSwitchDueTime;
962 }
963
964 // Ready to start a new event.
965 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 if (isAppSwitchDue) {
969 // The inbound queue is empty so the app switch key we were waiting
970 // for will never arrive. Stop waiting for it.
971 resetPendingAppSwitchLocked(false);
972 isAppSwitchDue = false;
973 }
974
975 // Synthesize a key repeat if appropriate.
976 if (mKeyRepeatState.lastKeyEntry) {
977 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
978 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
979 } else {
980 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
981 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
982 }
983 }
984 }
985
986 // Nothing to do if there is no pending event.
987 if (!mPendingEvent) {
988 return;
989 }
990 } else {
991 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700992 mPendingEvent = mInboundQueue.front();
993 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 traceInboundQueueLengthLocked();
995 }
996
997 // Poke user activity for this event.
998 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 // Now we have an event to dispatch.
1004 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013
1014 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001019 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 const ConfigurationChangedEntry& typedEntry =
1021 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 break;
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001027 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 const DeviceResetEntry& typedEntry =
1029 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 break;
1033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001036 std::shared_ptr<FocusEntry> typedEntry =
1037 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001038 dispatchFocusLocked(currentTime, typedEntry);
1039 done = true;
1040 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1041 break;
1042 }
1043
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001044 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1045 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1046 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1047 done = true;
1048 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1049 break;
1050 }
1051
Prabir Pradhan99987712020-11-10 18:43:05 -08001052 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1053 const auto typedEntry =
1054 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1055 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1056 done = true;
1057 break;
1058 }
1059
arthurhungb89ccb02020-12-30 16:19:01 +08001060 case EventEntry::Type::DRAG: {
1061 std::shared_ptr<DragEntry> typedEntry =
1062 std::static_pointer_cast<DragEntry>(mPendingEvent);
1063 dispatchDragLocked(currentTime, typedEntry);
1064 done = true;
1065 break;
1066 }
1067
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 resetPendingAppSwitchLocked(true);
1073 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 } else if (dropReason == DropReason::NOT_DROPPED) {
1075 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 }
1077 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001078 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1082 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 break;
1086 }
1087
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001088 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 std::shared_ptr<MotionEntry> motionEntry =
1090 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1092 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001094 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1098 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 }
Chris Yef59a2f42020-10-16 12:55:26 -07001103
1104 case EventEntry::Type::SENSOR: {
1105 std::shared_ptr<SensorEntry> sensorEntry =
1106 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1107 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1108 dropReason = DropReason::APP_SWITCH;
1109 }
1110 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1111 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1112 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1113 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1114 dropReason = DropReason::STALE;
1115 }
1116 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1117 done = true;
1118 break;
1119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
1121
1122 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
Michael Wright3a981722015-06-10 15:26:13 +01001126 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127
1128 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001129 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131}
1132
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001133bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1134 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1135}
1136
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001137/**
1138 * Return true if the events preceding this incoming motion event should be dropped
1139 * Return false otherwise (the default behaviour)
1140 */
1141bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001142 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001143 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001144
1145 // Optimize case where the current application is unresponsive and the user
1146 // decides to touch a window in a different application.
1147 // If the application takes too long to catch up then we drop all events preceding
1148 // the touch into the other window.
1149 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001150 const int32_t displayId = motionEntry.displayId;
1151 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001152 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001153
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001154 sp<WindowInfoHandle> touchedWindowHandle =
1155 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001156 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001157 touchedWindowHandle->getApplicationToken() !=
1158 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001159 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001160 ALOGI("Pruning input queue because user touched a different application while waiting "
1161 "for %s",
1162 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001163 return true;
1164 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001165
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001166 // Alternatively, maybe there's a spy window that could handle this event.
1167 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1168 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1169 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001170 const std::shared_ptr<Connection> connection =
1171 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001172 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001173 // This spy window could take more input. Drop all events preceding this
1174 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001176 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001177 mAwaitedFocusedApplication->getName().c_str());
1178 return true;
1179 }
1180 }
1181 }
1182
1183 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1184 // yet been processed by some connections, the dispatcher will wait for these motion
1185 // events to be processed before dispatching the key event. This is because these motion events
1186 // may cause a new window to be launched, which the user might expect to receive focus.
1187 // To prevent waiting forever for such events, just send the key to the currently focused window
1188 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1189 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1190 "just send the pending key event to the focused window.");
1191 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001192 }
1193 return false;
1194}
1195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001197 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 mInboundQueue.push_back(std::move(newEntry));
1199 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 traceInboundQueueLengthLocked();
1201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001203 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001204 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1205 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 // Optimize app switch latency.
1207 // If the application takes too long to catch up then we drop all events preceding
1208 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001215 if (DEBUG_APP_SWITCH) {
1216 ALOGD("App switch is pending!");
1217 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 mAppSwitchSawKeyDown = false;
1220 needWake = true;
1221 }
1222 }
1223 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001224
1225 // If a new up event comes in, and the pending event with same key code has been asked
1226 // to try again later because of the policy. We have to reset the intercept key wake up
1227 // time for it may have been handled in the policy and could be dropped.
1228 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1229 mPendingEvent->type == EventEntry::Type::KEY) {
1230 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1231 if (pendingKey.keyCode == keyEntry.keyCode &&
1232 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001233 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1234 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001235 pendingKey.interceptKeyWakeupTime = 0;
1236 needWake = true;
1237 }
1238 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 break;
1240 }
1241
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001242 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001243 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1244 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1246 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001251 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001252 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1253 break;
1254 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001255 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001256 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001257 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001258 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001259 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1260 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 // nothing to do
1262 break;
1263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265
1266 return needWake;
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001270 // Do not store sensor event in recent queue to avoid flooding the queue.
1271 if (entry->type != EventEntry::Type::SENSOR) {
1272 mRecentQueue.push_back(entry);
1273 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001274 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001275 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277}
1278
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001279sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1280 bool isStylus,
1281 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001283 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001284 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001285 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001286 continue;
1287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001289 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001290 if (!info.isSpy() &&
1291 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001292 return windowHandle;
1293 }
1294 }
1295 return nullptr;
1296}
1297
1298std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001299 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001300 if (touchedWindow == nullptr) {
1301 return {};
1302 }
1303 // Traverse windows from front to back until we encounter the touched window.
1304 std::vector<InputTarget> outsideTargets;
1305 const auto& windowHandles = getWindowHandlesLocked(displayId);
1306 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1307 if (windowHandle == touchedWindow) {
1308 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1309 // below the touched window will not get ACTION_OUTSIDE event.
1310 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001311 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001312
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001313 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001314 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001315 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1316 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001317 addPointerWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1318 pointerIds,
1319 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001322 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323}
1324
Prabir Pradhand65552b2021-10-07 11:23:50 -07001325std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001326 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001327 // Traverse windows from front to back and gather the touched spy windows.
1328 std::vector<sp<WindowInfoHandle>> spyWindows;
1329 const auto& windowHandles = getWindowHandlesLocked(displayId);
1330 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1331 const WindowInfo& info = *windowHandle->getInfo();
1332
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001333 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001334 continue;
1335 }
1336 if (!info.isSpy()) {
1337 // The first touched non-spy window was found, so return the spy windows touched so far.
1338 return spyWindows;
1339 }
1340 spyWindows.push_back(windowHandle);
1341 }
1342 return spyWindows;
1343}
1344
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001345void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 const char* reason;
1347 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001348 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001349 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001350 ALOGD("Dropped event because policy consumed it.");
1351 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001352 reason = "inbound event was dropped because the policy consumed it";
1353 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001354 case DropReason::DISABLED:
1355 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 ALOGI("Dropped event because input dispatch is disabled.");
1357 }
1358 reason = "inbound event was dropped because input dispatch is disabled";
1359 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001360 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001361 ALOGI("Dropped event because of pending overdue app switch.");
1362 reason = "inbound event was dropped because of pending overdue app switch";
1363 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001364 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 ALOGI("Dropped event because the current application is not responding and the user "
1366 "has started interacting with a different application.");
1367 reason = "inbound event was dropped because the current application is not responding "
1368 "and the user has started interacting with a different application";
1369 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001370 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371 ALOGI("Dropped event because it is stale.");
1372 reason = "inbound event was dropped because it is stale";
1373 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001374 case DropReason::NO_POINTER_CAPTURE:
1375 ALOGI("Dropped event because there is no window with Pointer Capture.");
1376 reason = "inbound event was dropped because there is no window with Pointer Capture";
1377 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 case DropReason::NOT_DROPPED: {
1379 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 }
1383
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001384 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001385 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001386 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001390 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1392 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001393 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 synthesizeCancelationEventsForAllConnectionsLocked(options);
1395 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001396 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1397 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001398 synthesizeCancelationEventsForAllConnectionsLocked(options);
1399 }
1400 break;
1401 }
Chris Yef59a2f42020-10-16 12:55:26 -07001402 case EventEntry::Type::SENSOR: {
1403 break;
1404 }
arthurhungb89ccb02020-12-30 16:19:01 +08001405 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1406 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001407 break;
1408 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001409 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001410 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001411 case EventEntry::Type::CONFIGURATION_CHANGED:
1412 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001413 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001414 break;
1415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 }
1417}
1418
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001419static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001420 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1421 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422}
1423
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001424bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1425 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1426 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1427 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428}
1429
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001430bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001431 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432}
1433
1434void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001435 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001437 if (DEBUG_APP_SWITCH) {
1438 if (handled) {
1439 ALOGD("App switch has arrived.");
1440 } else {
1441 ALOGD("App switch was abandoned.");
1442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444}
1445
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001447 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448}
1449
Prabir Pradhancef936d2021-07-21 16:17:52 +00001450bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001451 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 return false;
1453 }
1454
1455 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001456 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001458 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1459 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001460 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 return true;
1462}
1463
Prabir Pradhancef936d2021-07-21 16:17:52 +00001464void InputDispatcher::postCommandLocked(Command&& command) {
1465 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466}
1467
1468void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001469 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001470 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001471 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 releaseInboundEventLocked(entry);
1473 }
1474 traceInboundQueueLengthLocked();
1475}
1476
1477void InputDispatcher::releasePendingEventLocked() {
1478 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001480 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 }
1482}
1483
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001484void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001486 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001487 if (DEBUG_DISPATCH_CYCLE) {
1488 ALOGD("Injected inbound event was dropped.");
1489 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001490 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001493 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 }
1495 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496}
1497
1498void InputDispatcher::resetKeyRepeatLocked() {
1499 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001500 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502}
1503
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001504std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1505 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
Michael Wright2e732952014-09-24 13:26:59 -07001507 uint32_t policyFlags = entry->policyFlags &
1508 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 std::shared_ptr<KeyEntry> newEntry =
1511 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1512 entry->source, entry->displayId, policyFlags, entry->action,
1513 entry->flags, entry->keyCode, entry->scanCode,
1514 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 newEntry->syntheticRepeat = true;
1517 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001519 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520}
1521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001524 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1525 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527
1528 // Reset key repeating in case a keyboard device was added or removed or something.
1529 resetKeyRepeatLocked();
1530
1531 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001532 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1533 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001534 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001535 };
1536 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 return true;
1538}
1539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001540bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1541 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001542 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1543 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1544 entry.deviceId);
1545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546
liushenxiang42232912021-05-21 20:24:09 +08001547 // Reset key repeating in case a keyboard device was disabled or enabled.
1548 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1549 resetKeyRepeatLocked();
1550 }
1551
Michael Wrightfb04fd52022-11-24 22:31:11 +00001552 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001553 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001555
1556 // Remove all active pointers from this device
1557 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1558 touchState.removeAllPointersForDevice(entry.deviceId);
1559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 return true;
1561}
1562
Vishnu Nairad321cd2020-08-20 16:40:21 -07001563void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001564 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001565 if (mPendingEvent != nullptr) {
1566 // Move the pending event to the front of the queue. This will give the chance
1567 // for the pending event to get dispatched to the newly focused window
1568 mInboundQueue.push_front(mPendingEvent);
1569 mPendingEvent = nullptr;
1570 }
1571
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001572 std::unique_ptr<FocusEntry> focusEntry =
1573 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1574 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001575
1576 // This event should go to the front of the queue, but behind all other focus events
1577 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001579 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 [](const std::shared_ptr<EventEntry>& event) {
1581 return event->type == EventEntry::Type::FOCUS;
1582 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001583
1584 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001586}
1587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001589 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001590 if (channel == nullptr) {
1591 return; // Window has gone away
1592 }
1593 InputTarget target;
1594 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001595 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001596 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001597 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1598 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001599 std::string reason = std::string("reason=").append(entry->reason);
1600 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001601 dispatchEventLocked(currentTime, entry, {target});
1602}
1603
Prabir Pradhan99987712020-11-10 18:43:05 -08001604void InputDispatcher::dispatchPointerCaptureChangedLocked(
1605 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1606 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001607 dropReason = DropReason::NOT_DROPPED;
1608
Prabir Pradhan99987712020-11-10 18:43:05 -08001609 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001610 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001611
1612 if (entry->pointerCaptureRequest.enable) {
1613 // Enable Pointer Capture.
1614 if (haveWindowWithPointerCapture &&
1615 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001616 // This can happen if pointer capture is disabled and re-enabled before we notify the
1617 // app of the state change, so there is no need to notify the app.
1618 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1619 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001620 }
1621 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001622 // This can happen if a window requests capture and immediately releases capture.
1623 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001624 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001625 return;
1626 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001627 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1628 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1629 return;
1630 }
1631
Vishnu Nairc519ff72021-01-21 08:23:08 -08001632 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001633 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1634 mWindowTokenWithPointerCapture = token;
1635 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001636 // Disable Pointer Capture.
1637 // We do not check if the sequence number matches for requests to disable Pointer Capture
1638 // for two reasons:
1639 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1640 // to disable capture with the same sequence number: one generated by
1641 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1642 // Capture being disabled in InputReader.
1643 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1644 // actual Pointer Capture state that affects events being generated by input devices is
1645 // in InputReader.
1646 if (!haveWindowWithPointerCapture) {
1647 // Pointer capture was already forcefully disabled because of focus change.
1648 dropReason = DropReason::NOT_DROPPED;
1649 return;
1650 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001651 token = mWindowTokenWithPointerCapture;
1652 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001653 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001654 setPointerCaptureLocked(false);
1655 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001656 }
1657
1658 auto channel = getInputChannelLocked(token);
1659 if (channel == nullptr) {
1660 // Window has gone away, clean up Pointer Capture state.
1661 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001662 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001663 setPointerCaptureLocked(false);
1664 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001665 return;
1666 }
1667 InputTarget target;
1668 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001669 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001670 entry->dispatchInProgress = true;
1671 dispatchEventLocked(currentTime, entry, {target});
1672
1673 dropReason = DropReason::NOT_DROPPED;
1674}
1675
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001676void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1677 const std::shared_ptr<TouchModeEntry>& entry) {
1678 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001679 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001680 if (windowHandles.empty()) {
1681 return;
1682 }
1683 const std::vector<InputTarget> inputTargets =
1684 getInputTargetsFromWindowHandlesLocked(windowHandles);
1685 if (inputTargets.empty()) {
1686 return;
1687 }
1688 entry->dispatchInProgress = true;
1689 dispatchEventLocked(currentTime, entry, inputTargets);
1690}
1691
1692std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1693 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1694 std::vector<InputTarget> inputTargets;
1695 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001696 const sp<IBinder>& token = handle->getToken();
1697 if (token == nullptr) {
1698 continue;
1699 }
1700 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1701 if (channel == nullptr) {
1702 continue; // Window has gone away
1703 }
1704 InputTarget target;
1705 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001706 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001707 inputTargets.push_back(target);
1708 }
1709 return inputTargets;
1710}
1711
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001712bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001713 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001715 if (!entry->dispatchInProgress) {
1716 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1717 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1718 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1719 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001720 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // We have seen two identical key downs in a row which indicates that the device
1722 // driver is automatically generating key repeats itself. We take note of the
1723 // repeat here, but we disable our own next key repeat timer since it is clear that
1724 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001725 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1726 // Make sure we don't get key down from a different device. If a different
1727 // device Id has same key pressed down, the new device Id will replace the
1728 // current one to hold the key repeat with repeat count reset.
1729 // In the future when got a KEY_UP on the device id, drop it and do not
1730 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1732 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001733 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 } else {
1735 // Not a repeat. Save key down state in case we do see a repeat later.
1736 resetKeyRepeatLocked();
1737 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1738 }
1739 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001740 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1741 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001742 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001743 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001744 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1745 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 resetKeyRepeatLocked();
1748 }
1749
1750 if (entry->repeatCount == 1) {
1751 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1752 } else {
1753 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1754 }
1755
1756 entry->dispatchInProgress = true;
1757
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001758 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 }
1760
1761 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001762 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 if (currentTime < entry->interceptKeyWakeupTime) {
1764 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1765 *nextWakeupTime = entry->interceptKeyWakeupTime;
1766 }
1767 return false; // wait until next wakeup
1768 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001769 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 entry->interceptKeyWakeupTime = 0;
1771 }
1772
1773 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001774 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001776 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001777 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001778
1779 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1780 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1781 };
1782 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001783 // Poke user activity for keys not passed to user
1784 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 return false; // wait for the command to run
1786 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001787 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001789 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001790 if (*dropReason == DropReason::NOT_DROPPED) {
1791 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794
1795 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001796 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001797 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1799 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001800 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001801 // Poke user activity for undispatched keys
1802 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 return true;
1804 }
1805
1806 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001807 InputEventInjectionResult injectionResult;
1808 sp<WindowInfoHandle> focusedWindow =
1809 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1810 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return false;
1813 }
1814
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001815 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001816 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 return true;
1818 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001819 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1820
1821 std::vector<InputTarget> inputTargets;
1822 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001823 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001824 getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001826 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828
1829 // Dispatch the key.
1830 dispatchEventLocked(currentTime, entry, inputTargets);
1831 return true;
1832}
1833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001835 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1836 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1837 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1838 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1839 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1840 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1841 entry.metaState, entry.repeatCount, entry.downTime);
1842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843}
1844
Prabir Pradhancef936d2021-07-21 16:17:52 +00001845void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1846 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001847 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001848 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1849 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1850 "source=0x%x, sensorType=%s",
1851 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001852 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001853 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001854 auto command = [this, entry]() REQUIRES(mLock) {
1855 scoped_unlock unlock(mLock);
1856
1857 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001858 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001859 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001860 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1861 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001862 };
1863 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001864}
1865
1866bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1868 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001869 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001870 }
Chris Yef59a2f42020-10-16 12:55:26 -07001871 { // acquire lock
1872 std::scoped_lock _l(mLock);
1873
1874 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1875 std::shared_ptr<EventEntry> entry = *it;
1876 if (entry->type == EventEntry::Type::SENSOR) {
1877 it = mInboundQueue.erase(it);
1878 releaseInboundEventLocked(entry);
1879 }
1880 }
1881 }
1882 return true;
1883}
1884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001885bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001889 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 entry->dispatchInProgress = true;
1891
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001892 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 }
1894
1895 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001896 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001897 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001898 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1899 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 return true;
1901 }
1902
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001903 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001906 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 if (isPointerEvent) {
1910 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001911
1912 if (mDragState &&
1913 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1914 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1915 pilferPointersLocked(mDragState->dragWindow->getToken());
1916 }
1917
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001918 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001919 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001920 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1921 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 } else {
1923 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001924 sp<WindowInfoHandle> focusedWindow =
1925 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1926 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1927 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1928 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001929 InputTarget::Flags::FOREGROUND |
1930 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001931 getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001934 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 return false;
1936 }
1937
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001938 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001939 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001940 return true;
1941 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001943 CancelationOptions::Mode mode(
1944 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1945 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001946 CancelationOptions options(mode, "input event injection failed");
1947 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 return true;
1949 }
1950
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001951 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953
1954 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 dispatchEventLocked(currentTime, entry, inputTargets);
1956 return true;
1957}
1958
chaviw98318de2021-05-19 16:45:23 -05001959void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001960 bool isExiting, const int32_t rawX,
1961 const int32_t rawY) {
1962 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001963 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001964 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1965 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001966
1967 enqueueInboundEventLocked(std::move(dragEntry));
1968}
1969
1970void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1971 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1972 if (channel == nullptr) {
1973 return; // Window has gone away
1974 }
1975 InputTarget target;
1976 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001977 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001978 entry->dispatchInProgress = true;
1979 dispatchEventLocked(currentTime, entry, {target});
1980}
1981
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001982void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001983 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001984 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001985 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001986 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001987 "metaState=0x%x, buttonState=0x%x,"
1988 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001989 prefix, entry.eventTime, entry.deviceId,
1990 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1991 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1992 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1993 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07001995 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001996 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001997 "x=%f, y=%f, pressure=%f, size=%f, "
1998 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1999 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002000 i, entry.pointerProperties[i].id,
2001 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002002 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2003 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2004 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2005 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2006 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013}
2014
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002015void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2016 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002017 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002018 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002019 if (DEBUG_DISPATCH_CYCLE) {
2020 ALOGD("dispatchEventToCurrentInputTargets");
2021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002023 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2026
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002027 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002029 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002030 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002031 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002032 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002033 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002035 if (DEBUG_FOCUS) {
2036 ALOGD("Dropping event delivery to target with channel '%s' because it "
2037 "is no longer registered with the input dispatcher.",
2038 inputTarget.inputChannel->getName().c_str());
2039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
2041 }
2042}
2043
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002044void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002045 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2046 // If the policy decides to close the app, we will get a channel removal event via
2047 // unregisterInputChannel, and will clean up the connection that way. We are already not
2048 // sending new pointers to the connection when it blocked, but focused events will continue to
2049 // pile up.
2050 ALOGW("Canceling events for %s because it is unresponsive",
2051 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002052 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002053 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002054 "application not responding");
2055 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 }
2057}
2058
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002059void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002060 if (DEBUG_FOCUS) {
2061 ALOGD("Resetting ANR timeouts.");
2062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002065 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002066 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067}
2068
Tiger Huang721e26f2018-07-24 22:26:19 +08002069/**
2070 * Get the display id that the given event should go to. If this event specifies a valid display id,
2071 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2072 * Focused display is the display that the user most recently interacted with.
2073 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002074int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002075 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002076 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002077 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2079 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002080 break;
2081 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002082 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002083 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2084 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 break;
2086 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002087 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002088 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002089 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002090 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002091 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002092 case EventEntry::Type::SENSOR:
2093 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002094 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 return ADISPLAY_ID_NONE;
2096 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002097 }
2098 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2099}
2100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002101bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2102 const char* focusedWindowName) {
2103 if (mAnrTracker.empty()) {
2104 // already processed all events that we waited for
2105 mKeyIsWaitingForEventsTimeout = std::nullopt;
2106 return false;
2107 }
2108
2109 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2110 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002111 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002112 mKeyIsWaitingForEventsTimeout = currentTime +
2113 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2114 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 return true;
2116 }
2117
2118 // We still have pending events, and already started the timer
2119 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2120 return true; // Still waiting
2121 }
2122
2123 // Waited too long, and some connection still hasn't processed all motions
2124 // Just send the key to the focused window
2125 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2126 focusedWindowName);
2127 mKeyIsWaitingForEventsTimeout = std::nullopt;
2128 return false;
2129}
2130
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002131sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2132 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2133 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002134 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136
Tiger Huang721e26f2018-07-24 22:26:19 +08002137 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002138 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002139 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002140 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2141
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 // If there is no currently focused window and no focused application
2143 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002144 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2145 ALOGI("Dropping %s event because there is no focused window or focused application in "
2146 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002147 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002148 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150
Vishnu Nair062a8672021-09-03 16:07:44 -07002151 // Drop key events if requested by input feature
2152 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002153 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002154 }
2155
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002156 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2157 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2158 // start interacting with another application via touch (app switch). This code can be removed
2159 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2160 // an app is expected to have a focused window.
2161 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2162 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2163 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002164 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2165 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2166 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002167 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002168 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 ALOGW("Waiting because no window has focus but %s may eventually add a "
2170 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002171 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002172 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002173 outInjectionResult = InputEventInjectionResult::PENDING;
2174 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2176 // Already raised ANR. Drop the event
2177 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002178 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002180 } else {
2181 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002182 outInjectionResult = InputEventInjectionResult::PENDING;
2183 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 }
2185 }
2186
2187 // we have a valid, non-null focused window
2188 resetNoFocusedWindowTimeoutLocked();
2189
Prabir Pradhan5735a322022-04-11 17:23:34 +00002190 // Verify targeted injection.
2191 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2192 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002193 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2194 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
2196
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002197 if (focusedWindowHandle->getInfo()->inputConfig.test(
2198 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002199 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002200 outInjectionResult = InputEventInjectionResult::PENDING;
2201 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002202 }
2203
2204 // If the event is a key event, then we must wait for all previous events to
2205 // complete before delivering it because previous events may have the
2206 // side-effect of transferring focus to a different window and we want to
2207 // ensure that the following keys are sent to the new window.
2208 //
2209 // Suppose the user touches a button in a window then immediately presses "A".
2210 // If the button causes a pop-up window to appear then we want to ensure that
2211 // the "A" key is delivered to the new pop-up window. This is because users
2212 // often anticipate pending UI changes when typing on a keyboard.
2213 // To obtain this behavior, we must serialize key events with respect to all
2214 // prior input events.
2215 if (entry.type == EventEntry::Type::KEY) {
2216 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2217 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002218 outInjectionResult = InputEventInjectionResult::PENDING;
2219 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002223 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2224 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225}
2226
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002227/**
2228 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2229 * that are currently unresponsive.
2230 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002231std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2232 const std::vector<Monitor>& monitors) const {
2233 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002235 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002236 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002237 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002238 if (connection == nullptr) {
2239 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002240 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 return false;
2242 }
2243 if (!connection->responsive) {
2244 ALOGW("Unresponsive monitor %s will not get the new gesture",
2245 connection->inputChannel->getName().c_str());
2246 return false;
2247 }
2248 return true;
2249 });
2250 return responsiveMonitors;
2251}
2252
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002253std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002254 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002255 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002256 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002258 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 // For security reasons, we defer updating the touch state until we are sure that
2260 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002261 const int32_t displayId = entry.displayId;
2262 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002263 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
2265 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002266 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002268 // Copy current touch state into tempTouchState.
2269 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2270 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002271 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002273 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2274 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002275 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002276 }
2277
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002278 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279
2280 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2281 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2282 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002283 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2284 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002285 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002286 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2287 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002288 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2289 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2290 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002291 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002292
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002293 if (newGesture) {
2294 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002295 }
2296
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002297 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2298 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2299 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002302 if (isHoverAction) {
2303 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2304 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002305 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002306 }
2307
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2309 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002310 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002311 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002312 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002313 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2314 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002315 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002316 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002317 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002318
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002319 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002320 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002323 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002324 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002326 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002327 }
2328
Prabir Pradhan5735a322022-04-11 17:23:34 +00002329 // Verify targeted injection.
2330 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2331 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002332 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002333 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002334 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002335 }
2336
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002337 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002338 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002339 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2340 // New window supports splitting, but we should never split mouse events.
2341 isSplit = !isFromMouse;
2342 } else if (isSplit) {
2343 // New window does not support splitting but we have already split events.
2344 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002345 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2346 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002347 newTouchedWindowHandle = nullptr;
2348 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002349 } else {
2350 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002351 // be delivered to a new window which supports split touch. Pointers from a mouse device
2352 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002353 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002354 }
2355
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002356 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002357 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002358 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002359 // Process the foreground window first so that it is the first to receive the event.
2360 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002361 }
2362
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002363 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002364 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2365 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002366 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002367 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002368 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002369 }
2370
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002371 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002372 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 continue;
2374 }
2375
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002376 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002377 // The "windowHandle" is the target of this hovering pointer.
2378 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002379 }
2380
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002381 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002382 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002384 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2385 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002386 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002387 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388
2389 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 }
2392 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002393 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002394 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002395 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002396 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002397
2398 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002399
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002400 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002401 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002402 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002403 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2404 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2405 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId,
2406 pointerIds,
2407 isDownOrPointerDown
2408 ? std::make_optional(entry.eventTime)
2409 : std::nullopt);
2410 // If this is the pointer going down and the touched window has a wallpaper
2411 // then also add the touched wallpaper windows so they are locked in for the
2412 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2413 // SCROLL because the wallpaper engine only supports touch events. We would need to
2414 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2415 // handle these events.
2416 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002417 windowHandle->getInfo()->inputConfig.test(
2418 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2419 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2420 if (wallpaper != nullptr) {
2421 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2422 InputTarget::Flags::WINDOW_IS_OBSCURED |
2423 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2424 InputTarget::Flags::DISPATCH_AS_IS;
2425 if (isSplit) {
2426 wallpaperFlags |= InputTarget::Flags::SPLIT;
2427 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002428 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2429 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002430 }
2431 }
2432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002434
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002435 // If a window is already pilfering some pointers, give it this new pointer as well and
2436 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2437 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002438 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002439 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2440 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002441 // This window is already pilfering some pointers, and this new pointer is also
2442 // going to it. Therefore, take over this pointer and don't give it to anyone
2443 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002444 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002445 }
2446 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002447
2448 // Restrict all pilfered pointers to the pilfering windows.
2449 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 } else {
2451 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2452
2453 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002454 if (!tempTouchState.isDown(entry.deviceId) &&
2455 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
2456 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2457 << " is not down or we previously "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002458 "dropped the pointer down event in display "
2459 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002460 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002461 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002464 // If the pointer is not currently hovering, then ignore the event.
2465 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2466 const int32_t pointerId = entry.pointerProperties[0].id;
2467 if (oldState == nullptr ||
2468 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2469 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2470 "display "
2471 << displayId << ": " << entry.getDescription();
2472 outInjectionResult = InputEventInjectionResult::FAILED;
2473 return {};
2474 }
2475 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2476 }
2477
arthurhung6d4bed92021-03-17 11:59:33 +08002478 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002479
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002481 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002482 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002483 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002484 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002485 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002486 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002487 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002488 sp<WindowInfoHandle> newTouchedWindowHandle =
2489 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002490
Prabir Pradhan5735a322022-04-11 17:23:34 +00002491 // Verify targeted injection.
2492 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2493 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002494 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002495 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002496 }
2497
Vishnu Nair062a8672021-09-03 16:07:44 -07002498 // Drop touch events if requested by input feature
2499 if (newTouchedWindowHandle != nullptr &&
2500 shouldDropInput(entry, newTouchedWindowHandle)) {
2501 newTouchedWindowHandle = nullptr;
2502 }
2503
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002504 if (newTouchedWindowHandle != nullptr &&
2505 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002506 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002507 oldTouchedWindowHandle->getName().c_str(),
2508 newTouchedWindowHandle->getName().c_str(), displayId);
2509
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002511 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002512 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002513 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002514
2515 const TouchedWindow& touchedWindow =
2516 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002517 addPointerWindowTargetLocked(oldTouchedWindowHandle,
2518 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
2519 pointerIds,
2520 touchedWindow.getDownTimeInTarget(entry.deviceId),
2521 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
2523 // Make a slippery entrance into the new window.
2524 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002525 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002528 ftl::Flags<InputTarget::Flags> targetFlags =
2529 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002530 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002531 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002534 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002538 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002539 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002542 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2543 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002544
2545 // Check if the wallpaper window should deliver the corresponding event.
2546 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002547 tempTouchState, entry.deviceId, pointerId, targets);
2548 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2549 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
2551 }
Arthur Hung96483742022-11-15 03:30:48 +00002552
2553 // Update the pointerIds for non-splittable when it received pointer down.
2554 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2555 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002556 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002557 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2558 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2559 // Ignore drag window for it should just track one pointer.
2560 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2561 continue;
2562 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002563 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2564 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2565 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002566 }
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002570 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002571 {
2572 std::vector<TouchedWindow> hoveringWindows =
2573 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2574 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002575 std::optional<InputTarget> target =
2576 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002578 if (!target) {
2579 continue;
2580 }
2581 // Hardcode to single hovering pointer for now.
2582 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2583 pointerIds.set(entry.pointerProperties[0].id);
2584 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2585 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588
Prabir Pradhan5735a322022-04-11 17:23:34 +00002589 // Ensure that all touched windows are valid for injection.
2590 if (entry.injectionState != nullptr) {
2591 std::string errs;
2592 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002593 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2594 if (err) errs += "\n - " + *err;
2595 }
2596 if (!errs.empty()) {
2597 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002598 "%s:%s",
2599 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002600 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002601 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002602 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002603 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002604
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002605 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2606 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002608 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002609 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002610 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002611 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002612 for (InputTarget& target : targets) {
2613 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2614 sp<WindowInfoHandle> targetWindow =
2615 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2616 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2617 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620 }
2621 }
2622 }
2623
Harry Cuttsb166c002023-05-09 13:06:05 +00002624 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2625 // only want the system UI to handle these gestures.
2626 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2627 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2628 if (isTouchpadNavGesture) {
2629 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2630 }
2631
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002632 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002633 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002634 std::bitset<MAX_POINTER_ID + 1> touchingPointers =
2635 touchedWindow.getTouchingPointers(entry.deviceId);
2636 if (touchingPointers.none()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002637 continue;
2638 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002639 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2640 touchingPointers,
2641 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002642 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002643
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002644 // During targeted injection, only allow owned targets to receive events
2645 std::erase_if(targets, [&](const InputTarget& target) {
2646 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2647 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2648 if (err) {
2649 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2650 << ": " << (*err);
2651 return true;
2652 }
2653 return false;
2654 });
2655
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002656 if (targets.empty()) {
2657 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2658 outInjectionResult = InputEventInjectionResult::FAILED;
2659 return {};
2660 }
2661
2662 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2663 // window that is actually receiving the entire gesture.
2664 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2665 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2666 })) {
2667 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2668 << entry.getDescription();
2669 outInjectionResult = InputEventInjectionResult::FAILED;
2670 return {};
2671 }
2672
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002673 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002675 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2676 // Targets that we entered in a slippery way will now become AS-IS targets
2677 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
2678 touchedWindow.targetFlags.clear(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
2679 touchedWindow.targetFlags |= InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002680 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002681 }
2682
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002683 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002684 if (isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002685 if (oldState && oldState->isDown(entry.deviceId)) {
2686 // Started hovering, but the device is already down: reject the hover event
2687 LOG(ERROR) << "Got hover event " << entry.getDescription()
2688 << " but the device is already down " << oldState->dump();
2689 outInjectionResult = InputEventInjectionResult::FAILED;
2690 return {};
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002691 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002692 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2693 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002694 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002695 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002696 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002697 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002698 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2699 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002700 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2701 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2702 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 }
2704
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 // Save changes unless the action was scroll in which case the temporary touch
2706 // state was only valid for this one action.
2707 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002708 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002709 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 mTouchStatesByDisplay[displayId] = tempTouchState;
2711 } else {
2712 mTouchStatesByDisplay.erase(displayId);
2713 }
2714 }
2715
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002716 if (tempTouchState.windows.empty()) {
2717 mTouchStatesByDisplay.erase(displayId);
2718 }
2719
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002720 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721}
2722
arthurhung6d4bed92021-03-17 11:59:33 +08002723void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002724 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2725 // have an explicit reason to support it.
2726 constexpr bool isStylus = false;
2727
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002728 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002729 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002730 if (dropWindow) {
2731 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002732 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002733 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002734 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002735 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002736 }
2737 mDragState.reset();
2738}
2739
2740void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002741 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002742 return;
2743 }
2744
arthurhung6d4bed92021-03-17 11:59:33 +08002745 if (!mDragState->isStartDrag) {
2746 mDragState->isStartDrag = true;
2747 mDragState->isStylusButtonDownAtStart =
2748 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2749 }
2750
Arthur Hung54745652022-04-20 07:17:41 +00002751 // Find the pointer index by id.
2752 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002753 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002754 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2755 if (pointerProperties.id == mDragState->pointerId) {
2756 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002757 }
Arthur Hung54745652022-04-20 07:17:41 +00002758 }
arthurhung6d4bed92021-03-17 11:59:33 +08002759
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002760 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002761 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002762 }
2763
2764 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2765 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2766 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2767
2768 switch (maskedAction) {
2769 case AMOTION_EVENT_ACTION_MOVE: {
2770 // Handle the special case : stylus button no longer pressed.
2771 bool isStylusButtonDown =
2772 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2773 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2774 finishDragAndDrop(entry.displayId, x, y);
2775 return;
2776 }
2777
2778 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2779 // until we have an explicit reason to support it.
2780 constexpr bool isStylus = false;
2781
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002782 sp<WindowInfoHandle> hoverWindowHandle =
2783 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2784 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002785 // enqueue drag exit if needed.
2786 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2787 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2788 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002789 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002790 y);
2791 }
2792 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2793 }
2794 // enqueue drag location if needed.
2795 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002796 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002797 }
2798 break;
2799 }
2800
2801 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002802 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002803 break;
2804 }
2805 // The drag pointer is up.
2806 [[fallthrough]];
2807 case AMOTION_EVENT_ACTION_UP:
2808 finishDragAndDrop(entry.displayId, x, y);
2809 break;
2810 case AMOTION_EVENT_ACTION_CANCEL: {
2811 ALOGD("Receiving cancel when drag and drop.");
2812 sendDropWindowCommandLocked(nullptr, 0, 0);
2813 mDragState.reset();
2814 break;
2815 }
arthurhungb89ccb02020-12-30 16:19:01 +08002816 }
2817}
2818
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002819std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2820 const sp<android::gui::WindowInfoHandle>& windowHandle,
2821 ftl::Flags<InputTarget::Flags> targetFlags,
2822 std::optional<nsecs_t> firstDownTimeInTarget) const {
2823 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2824 if (inputChannel == nullptr) {
2825 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2826 return {};
2827 }
2828 InputTarget inputTarget;
2829 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002830 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002831 inputTarget.flags = targetFlags;
2832 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2833 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2834 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2835 if (displayInfoIt != mDisplayInfos.end()) {
2836 inputTarget.displayTransform = displayInfoIt->second.transform;
2837 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002838 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002839 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2840 }
2841 return inputTarget;
2842}
2843
chaviw98318de2021-05-19 16:45:23 -05002844void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002845 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002846 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002847 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002848 std::vector<InputTarget>::iterator it =
2849 std::find_if(inputTargets.begin(), inputTargets.end(),
2850 [&windowHandle](const InputTarget& inputTarget) {
2851 return inputTarget.inputChannel->getConnectionToken() ==
2852 windowHandle->getToken();
2853 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002854
chaviw98318de2021-05-19 16:45:23 -05002855 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002856
2857 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858 std::optional<InputTarget> target =
2859 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2860 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002861 return;
2862 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002863 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002864 it = inputTargets.end() - 1;
2865 }
2866
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002867 if (it->flags != targetFlags) {
2868 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2869 }
2870 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2871 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2872 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2873 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002874}
2875
2876void InputDispatcher::addPointerWindowTargetLocked(
2877 const sp<android::gui::WindowInfoHandle>& windowHandle,
2878 ftl::Flags<InputTarget::Flags> targetFlags, std::bitset<MAX_POINTER_ID + 1> pointerIds,
2879 std::optional<nsecs_t> firstDownTimeInTarget, std::vector<InputTarget>& inputTargets) const
2880 REQUIRES(mLock) {
2881 if (pointerIds.none()) {
2882 for (const auto& target : inputTargets) {
2883 LOG(INFO) << "Target: " << target;
2884 }
2885 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2886 return;
2887 }
2888 std::vector<InputTarget>::iterator it =
2889 std::find_if(inputTargets.begin(), inputTargets.end(),
2890 [&windowHandle](const InputTarget& inputTarget) {
2891 return inputTarget.inputChannel->getConnectionToken() ==
2892 windowHandle->getToken();
2893 });
2894
2895 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2896 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2897 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2898 // input targets for hovering pointers and for touching pointers.
2899 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2900 // target instead.
2901 if (it != inputTargets.end() && it->flags.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
2902 // Force the code below to create a new input target
2903 it = inputTargets.end();
2904 }
2905
2906 const WindowInfo* windowInfo = windowHandle->getInfo();
2907
2908 if (it == inputTargets.end()) {
2909 std::optional<InputTarget> target =
2910 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2911 if (!target) {
2912 return;
2913 }
2914 inputTargets.push_back(*target);
2915 it = inputTargets.end() - 1;
2916 }
2917
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002918 if (it->flags != targetFlags) {
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002919 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002920 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002921 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2922 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2923 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2924 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002925
chaviw1ff3d1e2020-07-01 15:53:47 -07002926 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927}
2928
Michael Wright3dd60e22019-03-27 22:06:44 +00002929void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002930 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002931 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2932 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002933
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002934 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2935 InputTarget target;
2936 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002937 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002938 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2939 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002940 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2941 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002942 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002943 target.setDefaultPointerTransform(target.displayTransform);
2944 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 }
2946}
2947
Robert Carrc9bf1d32020-04-13 17:21:08 -07002948/**
2949 * Indicate whether one window handle should be considered as obscuring
2950 * another window handle. We only check a few preconditions. Actually
2951 * checking the bounds is left to the caller.
2952 */
chaviw98318de2021-05-19 16:45:23 -05002953static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2954 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002955 // Compare by token so cloned layers aren't counted
2956 if (haveSameToken(windowHandle, otherHandle)) {
2957 return false;
2958 }
2959 auto info = windowHandle->getInfo();
2960 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002961 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002962 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002963 } else if (otherInfo->alpha == 0 &&
2964 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002965 // Those act as if they were invisible, so we don't need to flag them.
2966 // We do want to potentially flag touchable windows even if they have 0
2967 // opacity, since they can consume touches and alter the effects of the
2968 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002969 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002970 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2971 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002972 } else if (info->ownerUid == otherInfo->ownerUid) {
2973 // If ownerUid is the same we don't generate occlusion events as there
2974 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002975 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002976 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002977 return false;
2978 } else if (otherInfo->displayId != info->displayId) {
2979 return false;
2980 }
2981 return true;
2982}
2983
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002984/**
2985 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2986 * untrusted, one should check:
2987 *
2988 * 1. If result.hasBlockingOcclusion is true.
2989 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2990 * BLOCK_UNTRUSTED.
2991 *
2992 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2993 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2994 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2995 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2996 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2997 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2998 *
2999 * If neither of those is true, then it means the touch can be allowed.
3000 */
3001InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003002 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3003 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003004 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003005 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003006 TouchOcclusionInfo info;
3007 info.hasBlockingOcclusion = false;
3008 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003009 info.obscuringUid = gui::Uid::INVALID;
3010 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003011 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003012 if (windowHandle == otherHandle) {
3013 break; // All future windows are below us. Exit early.
3014 }
chaviw98318de2021-05-19 16:45:23 -05003015 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003016 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3017 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003018 if (DEBUG_TOUCH_OCCLUSION) {
3019 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003020 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003021 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003022 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3023 // we perform the checks below to see if the touch can be propagated or not based on the
3024 // window's touch occlusion mode
3025 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3026 info.hasBlockingOcclusion = true;
3027 info.obscuringUid = otherInfo->ownerUid;
3028 info.obscuringPackage = otherInfo->packageName;
3029 break;
3030 }
3031 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003032 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003033 float opacity =
3034 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3035 // Given windows A and B:
3036 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3037 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3038 opacityByUid[uid] = opacity;
3039 if (opacity > info.obscuringOpacity) {
3040 info.obscuringOpacity = opacity;
3041 info.obscuringUid = uid;
3042 info.obscuringPackage = otherInfo->packageName;
3043 }
3044 }
3045 }
3046 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003047 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003048 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003049 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003050 return info;
3051}
3052
chaviw98318de2021-05-19 16:45:23 -05003053std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003054 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003055 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003056 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3057 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3058 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003059 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003060 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003061 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3062 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003063 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3064 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3065 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003066 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003067}
3068
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003069bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3070 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003071 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3072 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003073 return false;
3074 }
3075 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003076 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003077 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003078 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003079 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3080 return false;
3081 }
3082 return true;
3083}
3084
chaviw98318de2021-05-19 16:45:23 -05003085bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003088 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3089 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003090 if (windowHandle == otherHandle) {
3091 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 }
chaviw98318de2021-05-19 16:45:23 -05003093 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003094 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003095 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 return true;
3097 }
3098 }
3099 return false;
3100}
3101
chaviw98318de2021-05-19 16:45:23 -05003102bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003103 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003104 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3105 const WindowInfo* windowInfo = windowHandle->getInfo();
3106 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003107 if (windowHandle == otherHandle) {
3108 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003109 }
chaviw98318de2021-05-19 16:45:23 -05003110 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003111 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003112 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003113 return true;
3114 }
3115 }
3116 return false;
3117}
3118
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003119std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003120 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003121 if (applicationHandle != nullptr) {
3122 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003123 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 } else {
3125 return applicationHandle->getName();
3126 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003127 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003128 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003130 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 }
3132}
3133
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003135 if (!isUserActivityEvent(eventEntry)) {
3136 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003137 return;
3138 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003139 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003140 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003141 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003142 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003143 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003144 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003145 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
3147 }
3148
3149 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003150 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003152 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3153 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 return;
3155 }
Josep del Riob3981622023-04-18 15:49:45 +00003156 if (windowDisablingUserActivityInfo != nullptr) {
3157 if (DEBUG_DISPATCH_CYCLE) {
3158 ALOGD("Not poking user activity: disabled by window '%s'.",
3159 windowDisablingUserActivityInfo->name.c_str());
3160 }
3161 return;
3162 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003163 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 eventType = USER_ACTIVITY_EVENT_TOUCH;
3165 }
3166 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003168 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003169 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3170 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 return;
3172 }
Josep del Riob3981622023-04-18 15:49:45 +00003173 // If the key code is unknown, we don't consider it user activity
3174 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3175 return;
3176 }
3177 // Don't inhibit events that were intercepted or are not passed to
3178 // the apps, like system shortcuts
3179 if (windowDisablingUserActivityInfo != nullptr &&
3180 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3181 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3182 if (DEBUG_DISPATCH_CYCLE) {
3183 ALOGD("Not poking user activity: disabled by window '%s'.",
3184 windowDisablingUserActivityInfo->name.c_str());
3185 }
3186 return;
3187 }
3188
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 eventType = USER_ACTIVITY_EVENT_BUTTON;
3190 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003192 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003193 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003194 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003195 break;
3196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198
Prabir Pradhancef936d2021-07-21 16:17:52 +00003199 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3200 REQUIRES(mLock) {
3201 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003202 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003203 };
3204 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205}
3206
3207void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003208 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003209 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003210 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003211 ATRACE_NAME_IF(ATRACE_ENABLED(),
3212 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3213 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003214 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003215 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003216 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003217 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003218 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003219 inputTarget.getPointerInfoString().c_str());
3220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221
3222 // Skip this event if the connection status is not normal.
3223 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003224 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003225 if (DEBUG_DISPATCH_CYCLE) {
3226 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003227 connection->getInputChannelName().c_str(),
3228 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 return;
3231 }
3232
3233 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003234 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003235 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003236 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003237 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003239 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003240 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003241 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3242 logDispatchStateLocked();
3243 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3244 "target on connection "
3245 << connection->getInputChannelName() << " for "
3246 << originalMotionEntry.getDescription();
3247 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003248 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003249 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3250 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 if (!splitMotionEntry) {
3252 return; // split event was dropped
3253 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003254 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3255 std::string reason = std::string("reason=pointer cancel on split window");
3256 android_log_event_list(LOGTAG_INPUT_CANCEL)
3257 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3258 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003259 if (DEBUG_FOCUS) {
3260 ALOGD("channel '%s' ~ Split motion event.",
3261 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003262 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003263 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003264 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3265 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 return;
3267 }
3268 }
3269
3270 // Not splitting. Enqueue dispatch entries for the event as is.
3271 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3272}
3273
3274void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003275 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003276 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003277 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003278 ATRACE_NAME_IF(ATRACE_ENABLED(),
3279 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3280 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003281 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3282 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003283
hongzuo liu95785e22022-09-06 02:51:35 +00003284 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003287 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003288 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003289 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003290 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003291 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003292 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003293 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003295 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003297 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
3300 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003301 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 startDispatchCycleLocked(currentTime, connection);
3303 }
3304}
3305
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003306void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003308 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003309 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003310 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3311 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 return;
3313 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003314
3315 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3316 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
3318 // This is a new event.
3319 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003320 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003321 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003323 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3324 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003325 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003327 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003328 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3331 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003332 LOG(WARNING) << "channel " << connection->getInputChannelName()
3333 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 return; // skip the inconsistent event
3335 }
3336 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003339 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003340 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003341 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3342 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3343 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3344 static_cast<int32_t>(IdGenerator::Source::OTHER);
3345 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003346 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003348 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003350 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003352 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003354 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3356 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003357 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 }
3359 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003360 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3361 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003362 if (DEBUG_DISPATCH_CYCLE) {
3363 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3364 "enter event",
3365 connection->getInputChannelName().c_str());
3366 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003367 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3368 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003372 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3373 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3374 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003375 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3377 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003378 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003382 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3383 // devices being active at the same time in the same window, so if a new device is
3384 // active, cancel the gesture from the old device.
3385
3386 std::unique_ptr<EventEntry> cancelEvent =
3387 connection->inputState
3388 .cancelConflictingInputStream(motionEntry,
3389 dispatchEntry->resolvedAction);
3390 if (cancelEvent != nullptr) {
3391 LOG(INFO) << "Canceling pointers for device " << motionEntry.deviceId << " in "
3392 << connection->getInputChannelName() << " with event "
3393 << cancelEvent->getDescription();
3394 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3395 createDispatchEntry(inputTarget, std::move(cancelEvent),
3396 InputTarget::Flags::DISPATCH_AS_IS);
3397
3398 // Send these cancel events to the queue before sending the event from the new
3399 // device.
3400 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3401 }
3402
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3404 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003405 LOG(WARNING) << "channel " << connection->getInputChannelName()
3406 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 return; // skip the inconsistent event
3408 }
3409
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003410 dispatchEntry->resolvedEventId =
3411 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3412 ? mIdGenerator.nextId()
3413 : motionEntry.id;
3414 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3415 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3416 ") to MotionEvent(id=0x%" PRIx32 ").",
3417 motionEntry.id, dispatchEntry->resolvedEventId);
3418 ATRACE_NAME(message.c_str());
3419 }
3420
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003421 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3422 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3423 // Skip reporting pointer down outside focus to the policy.
3424 break;
3425 }
3426
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003427 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003428 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429
3430 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003432 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003433 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003434 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3435 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003436 break;
3437 }
Chris Yef59a2f42020-10-16 12:55:26 -07003438 case EventEntry::Type::SENSOR: {
3439 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3440 break;
3441 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003442 case EventEntry::Type::CONFIGURATION_CHANGED:
3443 case EventEntry::Type::DEVICE_RESET: {
3444 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003445 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003446 break;
3447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449
3450 // Remember that we are waiting for this dispatch to complete.
3451 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003452 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 }
3454
3455 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003456 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003457 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003458}
3459
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003460/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003461 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003463 * The first role is to log input interaction with windows, which helps determine what the user was
3464 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3465 * that user started interacting with launcher window, as well as any other window that received
3466 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3467 * when the set of tokens that received the event changes. It is not logged again as long as the
3468 * user is interacting with the same windows.
3469 *
3470 * The second role is to track input device activity for metrics collection. For each input event,
3471 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3472 * input_interaction logs, the device interaction is reported even when the set of interaction
3473 * tokens do not change.
3474 *
3475 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3476 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003477 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003478void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3479 const std::vector<InputTarget>& targets) {
3480 int32_t deviceId;
3481 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003482 // Skip ACTION_UP events, and all events other than keys and motions
3483 if (entry.type == EventEntry::Type::KEY) {
3484 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3485 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3486 return;
3487 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003488 deviceId = keyEntry.deviceId;
3489 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 } else if (entry.type == EventEntry::Type::MOTION) {
3491 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3492 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003493 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3494 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003495 return;
3496 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003497 deviceId = motionEntry.deviceId;
3498 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003499 } else {
3500 return; // Not a key or a motion
3501 }
3502
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003503 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003504 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003505 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003506 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003507 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003508 continue; // Skip windows that receive ACTION_OUTSIDE
3509 }
3510
3511 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003512 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003513 if (connection == nullptr) {
3514 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003515 }
3516 newConnectionTokens.insert(std::move(token));
3517 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003518 if (target.windowHandle) {
3519 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3520 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003521 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003522
3523 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3524 REQUIRES(mLock) {
3525 scoped_unlock unlock(mLock);
3526 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3527 };
3528 postCommandLocked(std::move(command));
3529
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003530 if (newConnectionTokens == mInteractionConnectionTokens) {
3531 return; // no change
3532 }
3533 mInteractionConnectionTokens = newConnectionTokens;
3534
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003535 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003536 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003537 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003538 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003539 std::string message = "Interaction with: " + targetList;
3540 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003541 message += "<none>";
3542 }
3543 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3544}
3545
chaviwfd6d3512019-03-25 13:23:49 -07003546void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003547 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003548 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003549 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3550 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003551 return;
3552 }
3553
Vishnu Nairc519ff72021-01-21 08:23:08 -08003554 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003555 if (focusedToken == token) {
3556 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003557 return;
3558 }
3559
Prabir Pradhancef936d2021-07-21 16:17:52 +00003560 auto command = [this, token]() REQUIRES(mLock) {
3561 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003562 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003563 };
3564 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565}
3566
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003567status_t InputDispatcher::publishMotionEvent(Connection& connection,
3568 DispatchEntry& dispatchEntry) const {
3569 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3570 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3571
3572 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003573 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003574
3575 // Set the X and Y offset and X and Y scale depending on the input source.
3576 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003577 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003578 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3579 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003580 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003581 scaledCoords[i] = motionEntry.pointerCoords[i];
3582 // Don't apply window scale here since we don't want scale to affect raw
3583 // coordinates. The scale will be sent back to the client and applied
3584 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003585 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003586 }
3587 usingCoords = scaledCoords;
3588 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003589 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003590 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003591 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003592 scaledCoords[i].clear();
3593 }
3594 usingCoords = scaledCoords;
3595 }
3596
3597 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3598
3599 // Publish the motion event.
3600 return connection.inputPublisher
3601 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3602 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3603 std::move(hmac), dispatchEntry.resolvedAction,
3604 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3605 motionEntry.edgeFlags, motionEntry.metaState,
3606 motionEntry.buttonState, motionEntry.classification,
3607 dispatchEntry.transform, motionEntry.xPrecision,
3608 motionEntry.yPrecision, motionEntry.xCursorPosition,
3609 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3610 motionEntry.downTime, motionEntry.eventTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003611 motionEntry.getPointerCount(), motionEntry.pointerProperties.data(),
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003612 usingCoords);
3613}
3614
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003616 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003617 ATRACE_NAME_IF(ATRACE_ENABLED(),
3618 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3619 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003620 if (DEBUG_DISPATCH_CYCLE) {
3621 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003624 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003625 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003627 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003628 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629
3630 // Publish the event.
3631 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3633 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003634 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003635 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3636 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003637 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003638 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3639 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003642 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003643 status = connection->inputPublisher
3644 .publishKeyEvent(dispatchEntry->seq,
3645 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3646 keyEntry.source, keyEntry.displayId,
3647 std::move(hmac), dispatchEntry->resolvedAction,
3648 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3649 keyEntry.scanCode, keyEntry.metaState,
3650 keyEntry.repeatCount, keyEntry.downTime,
3651 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003652 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 }
3654
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003655 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003656 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003657 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3658 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003659 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003660 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 break;
3662 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003663
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003664 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003665 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003666 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003667 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003668 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003669 break;
3670 }
3671
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003672 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3673 const TouchModeEntry& touchModeEntry =
3674 static_cast<const TouchModeEntry&>(eventEntry);
3675 status = connection->inputPublisher
3676 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3677 touchModeEntry.inTouchMode);
3678
3679 break;
3680 }
3681
Prabir Pradhan99987712020-11-10 18:43:05 -08003682 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3683 const auto& captureEntry =
3684 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3685 status = connection->inputPublisher
3686 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003687 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003688 break;
3689 }
3690
arthurhungb89ccb02020-12-30 16:19:01 +08003691 case EventEntry::Type::DRAG: {
3692 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3693 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3694 dragEntry.id, dragEntry.x,
3695 dragEntry.y,
3696 dragEntry.isExiting);
3697 break;
3698 }
3699
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003700 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003701 case EventEntry::Type::DEVICE_RESET:
3702 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003703 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003704 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003705 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
3708
3709 // Check the result.
3710 if (status) {
3711 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003712 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 "This is unexpected because the wait queue is empty, so the pipe "
3715 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003716 "event to it, status=%s(%d)",
3717 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3718 status);
Harry Cutts33476232023-01-30 19:57:29 +00003719 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 } else {
3721 // Pipe is full and we are waiting for the app to finish process some events
3722 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003723 if (DEBUG_DISPATCH_CYCLE) {
3724 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3725 "waiting for the application to catch up",
3726 connection->getInputChannelName().c_str());
3727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 }
3729 } else {
3730 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003731 "status=%s(%d)",
3732 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3733 status);
Harry Cutts33476232023-01-30 19:57:29 +00003734 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
3736 return;
3737 }
3738
3739 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003740 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3741 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3742 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003743 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003744 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003745 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003746 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003747 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749}
3750
chaviw09c8d2d2020-08-24 15:48:26 -07003751std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3752 size_t size;
3753 switch (event.type) {
3754 case VerifiedInputEvent::Type::KEY: {
3755 size = sizeof(VerifiedKeyEvent);
3756 break;
3757 }
3758 case VerifiedInputEvent::Type::MOTION: {
3759 size = sizeof(VerifiedMotionEvent);
3760 break;
3761 }
3762 }
3763 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3764 return mHmacKeyManager.sign(start, size);
3765}
3766
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003767const std::array<uint8_t, 32> InputDispatcher::getSignature(
3768 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003769 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003770 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003771 // Only sign events up and down events as the purely move events
3772 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003773 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003774 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003775
3776 VerifiedMotionEvent verifiedEvent =
3777 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3778 verifiedEvent.actionMasked = actionMasked;
3779 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3780 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003781}
3782
3783const std::array<uint8_t, 32> InputDispatcher::getSignature(
3784 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3785 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3786 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3787 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003788 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003789}
3790
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003792 const std::shared_ptr<Connection>& connection,
3793 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003794 if (DEBUG_DISPATCH_CYCLE) {
3795 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3796 connection->getInputChannelName().c_str(), seq, toString(handled));
3797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003799 if (connection->status == Connection::Status::BROKEN ||
3800 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 return;
3802 }
3803
3804 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003805 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3806 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3807 };
3808 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809}
3810
3811void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003812 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003814 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003815 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3816 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818
3819 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003820 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003821 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003822 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003823 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824
3825 // The connection appears to be unrecoverably broken.
3826 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003827 if (connection->status == Connection::Status::NORMAL) {
3828 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829
3830 if (notify) {
3831 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003832 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3833 connection->getInputChannelName().c_str());
3834
3835 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003836 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003837 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003838 };
3839 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 }
3841 }
3842}
3843
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003844void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003845 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003846 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003847 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849}
3850
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003851void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003853 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855}
3856
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003857int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3858 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003859 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003860 if (connection == nullptr) {
3861 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3862 connectionToken.get(), events);
3863 return 0; // remove the callback
3864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003866 bool notify;
3867 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3868 if (!(events & ALOOPER_EVENT_INPUT)) {
3869 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3870 "events=0x%x",
3871 connection->getInputChannelName().c_str(), events);
3872 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 nsecs_t currentTime = now();
3876 bool gotOne = false;
3877 status_t status = OK;
3878 for (;;) {
3879 Result<InputPublisher::ConsumerResponse> result =
3880 connection->inputPublisher.receiveConsumerResponse();
3881 if (!result.ok()) {
3882 status = result.error().code();
3883 break;
3884 }
3885
3886 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3887 const InputPublisher::Finished& finish =
3888 std::get<InputPublisher::Finished>(*result);
3889 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3890 finish.consumeTime);
3891 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003892 if (shouldReportMetricsForConnection(*connection)) {
3893 const InputPublisher::Timeline& timeline =
3894 std::get<InputPublisher::Timeline>(*result);
3895 mLatencyTracker
3896 .trackGraphicsLatency(timeline.inputEventId,
3897 connection->inputChannel->getConnectionToken(),
3898 std::move(timeline.graphicsTimeline));
3899 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003900 }
3901 gotOne = true;
3902 }
3903 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003904 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003905 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 return 1;
3907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 }
3909
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003910 notify = status != DEAD_OBJECT || !connection->monitor;
3911 if (notify) {
3912 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3913 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3914 status);
3915 }
3916 } else {
3917 // Monitor channels are never explicitly unregistered.
3918 // We do it automatically when the remote endpoint is closed so don't warn about them.
3919 const bool stillHaveWindowHandle =
3920 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3921 notify = !connection->monitor && stillHaveWindowHandle;
3922 if (notify) {
3923 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3924 connection->getInputChannelName().c_str(), events);
3925 }
3926 }
3927
3928 // Remove the channel.
3929 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3930 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931}
3932
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003933void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003935 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003936 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 }
3938}
3939
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003940void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003941 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003942 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003943 for (const Monitor& monitor : monitors) {
3944 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003945 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003946 }
3947}
3948
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003950 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003951 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003952 if (connection == nullptr) {
3953 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003955
3956 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957}
3958
3959void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003960 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li5af92f92023-07-14 14:36:22 +08003961 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3962 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3963 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3964 LOG(INFO) << __func__
3965 << ": Canceling drag and drop because the pointers for the drag window are being "
3966 "canceled.";
3967 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3968 mDragState.reset();
3969 }
3970
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003971 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 return;
3973 }
3974
3975 nsecs_t currentTime = now();
3976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003977 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003978 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980 if (cancelationEvents.empty()) {
3981 return;
3982 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003983 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3984 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003985 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003986 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003987 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003988 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003989
Arthur Hungb3307ee2021-10-14 10:57:37 +00003990 std::string reason = std::string("reason=").append(options.reason);
3991 android_log_event_list(LOGTAG_INPUT_CANCEL)
3992 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3993
hongzuo liu95785e22022-09-06 02:51:35 +00003994 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003995 // The target to use if we don't find a window associated with the channel.
3996 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3997 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3998 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003999
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004000 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004001 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004002 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004003
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004004 switch (cancelationEventEntry->type) {
4005 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004006 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004007 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4008 ? std::make_optional(keyEntry.displayId)
4009 : std::nullopt;
4010 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
4011 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004012 keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004013 } else {
4014 targets.emplace_back(fallbackTarget);
4015 }
4016 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004017 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004019 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004020 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004021 const std::optional<int32_t> targetDisplay =
4022 motionEntry.displayId != ADISPLAY_ID_NONE
4023 ? std::make_optional(motionEntry.displayId)
4024 : std::nullopt;
4025 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004026 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004027 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004028 pointerIndex++) {
4029 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4030 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004031 addPointerWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
4032 pointerIds, motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004033 } else {
4034 targets.emplace_back(fallbackTarget);
4035 const auto it = mDisplayInfos.find(motionEntry.displayId);
4036 if (it != mDisplayInfos.end()) {
4037 targets.back().displayTransform = it->second.transform;
4038 targets.back().setDefaultPointerTransform(it->second.transform);
4039 }
4040 }
4041 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004044 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004045 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004046 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4047 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004048 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004049 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004050 break;
4051 }
4052 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004053 case EventEntry::Type::DEVICE_RESET:
4054 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004055 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004056 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004057 break;
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 }
4060
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004061 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4062 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004063 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004065
hongzuo liu95785e22022-09-06 02:51:35 +00004066 // If the outbound queue was previously empty, start the dispatch cycle going.
4067 if (wasEmpty && !connection->outboundQueue.empty()) {
4068 startDispatchCycleLocked(currentTime, connection);
4069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070}
4071
Svet Ganov5d3bc372020-01-26 23:11:07 -08004072void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004073 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004074 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004075 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004076 return;
4077 }
4078
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004080 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004081
4082 if (downEvents.empty()) {
4083 return;
4084 }
4085
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004087 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4088 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004089 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004090
chaviw98318de2021-05-19 16:45:23 -05004091 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004092 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004093
hongzuo liu95785e22022-09-06 02:51:35 +00004094 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004095 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004096 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004097 switch (downEventEntry->type) {
4098 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004099 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4100 if (windowHandle != nullptr) {
4101 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004102 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004103 pointerIndex++) {
4104 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4105 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004106 addPointerWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4107 motionEntry.downTime, targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004108 } else {
4109 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4110 .flags = targetFlags});
4111 const auto it = mDisplayInfos.find(motionEntry.displayId);
4112 if (it != mDisplayInfos.end()) {
4113 targets.back().displayTransform = it->second.transform;
4114 targets.back().setDefaultPointerTransform(it->second.transform);
4115 }
4116 }
4117 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004118 break;
4119 }
4120
4121 case EventEntry::Type::KEY:
4122 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004123 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004124 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004125 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004126 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004127 case EventEntry::Type::SENSOR:
4128 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004129 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004130 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004131 break;
4132 }
4133 }
4134
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004135 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4136 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004137 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004138 }
4139
hongzuo liu95785e22022-09-06 02:51:35 +00004140 // If the outbound queue was previously empty, start the dispatch cycle going.
4141 if (wasEmpty && !connection->outboundQueue.empty()) {
4142 startDispatchCycleLocked(downTime, connection);
4143 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004144}
4145
Arthur Hungc539dbb2022-12-08 07:45:36 +00004146void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4147 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4148 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004149 std::shared_ptr<Connection> wallpaperConnection =
4150 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004151 if (wallpaperConnection != nullptr) {
4152 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4153 }
4154 }
4155}
4156
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004157std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004158 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4159 nsecs_t splitDownTime) {
4160 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
4162 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004163 std::vector<PointerProperties> splitPointerProperties;
4164 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004166 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 uint32_t splitPointerCount = 0;
4168
4169 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004172 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004174 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004176 splitPointerProperties.push_back(pointerProperties);
4177 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 splitPointerCount += 1;
4179 }
4180 }
4181
4182 if (splitPointerCount != pointerIds.count()) {
4183 // This is bad. We are missing some of the pointers that we expected to deliver.
4184 // Most likely this indicates that we received an ACTION_MOVE events that has
4185 // different pointer ids than we expected based on the previous ACTION_DOWN
4186 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4187 // in this way.
4188 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004189 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004190 "a broken sequence of pointer ids from the input device: %s",
4191 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004192 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004195 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4198 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004199 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004201 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004203 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 if (pointerIds.count() == 1) {
4205 // The first/last pointer went down/up.
4206 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004208 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4209 ? AMOTION_EVENT_ACTION_CANCEL
4210 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 } else {
4212 // A secondary pointer went down/up.
4213 uint32_t splitPointerIndex = 0;
4214 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4215 splitPointerIndex += 1;
4216 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 action = maskedAction |
4218 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 }
4220 } else {
4221 // An unrelated pointer changed.
4222 action = AMOTION_EVENT_ACTION_MOVE;
4223 }
4224 }
4225
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004226 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4227 logDispatchStateLocked();
4228 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4229 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4230 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004231 }
4232
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004233 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004234 ATRACE_NAME_IF(ATRACE_ENABLED(),
4235 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4236 ").",
4237 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 std::unique_ptr<MotionEntry> splitMotionEntry =
4239 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4240 originalMotionEntry.deviceId, originalMotionEntry.source,
4241 originalMotionEntry.displayId,
4242 originalMotionEntry.policyFlags, action,
4243 originalMotionEntry.actionButton,
4244 originalMotionEntry.flags, originalMotionEntry.metaState,
4245 originalMotionEntry.buttonState,
4246 originalMotionEntry.classification,
4247 originalMotionEntry.edgeFlags,
4248 originalMotionEntry.xPrecision,
4249 originalMotionEntry.yPrecision,
4250 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004251 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004252 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004254 if (originalMotionEntry.injectionState) {
4255 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 splitMotionEntry->injectionState->refCount += 1;
4257 }
4258
4259 return splitMotionEntry;
4260}
4261
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004262void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4263 std::scoped_lock _l(mLock);
4264 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4265}
4266
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004267void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004268 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004269 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
Antonio Kantekf16f2832021-09-28 04:39:20 +00004272 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004274 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004277 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 } // release lock
4280
4281 if (needWake) {
4282 mLooper->wake();
4283 }
4284}
4285
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004286void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004287 ALOGD_IF(debugInboundEventDetails(),
4288 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4289 ", deviceId=%d, source=%s, displayId=%" PRId32
4290 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4291 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004292 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4293 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4294 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004295 Result<void> keyCheck = validateKeyEvent(args.action);
4296 if (!keyCheck.ok()) {
4297 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 return;
4299 }
4300
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004301 uint32_t policyFlags = args.policyFlags;
4302 int32_t flags = args.flags;
4303 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004304 // InputDispatcher tracks and generates key repeats on behalf of
4305 // whatever notifies it, so repeatCount should always be set to 0
4306 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4308 policyFlags |= POLICY_FLAG_VIRTUAL;
4309 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 if (policyFlags & POLICY_FLAG_FUNCTION) {
4312 metaState |= AMETA_FUNCTION_ON;
4313 }
4314
4315 policyFlags |= POLICY_FLAG_TRUSTED;
4316
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004317 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004319 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4320 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4321 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
Michael Wright2b3c3302018-03-02 17:19:13 +00004323 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004324 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004325 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4326 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329
Antonio Kantekf16f2832021-09-28 04:39:20 +00004330 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 { // acquire lock
4332 mLock.lock();
4333
4334 if (shouldSendKeyToInputFilterLocked(args)) {
4335 mLock.unlock();
4336
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004337 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004338 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 return; // event was consumed by the filter
4340 }
4341
4342 mLock.lock();
4343 }
4344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004345 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004346 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4347 args.displayId, policyFlags, args.action, flags, keyCode,
4348 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 mLock.unlock();
4352 } // release lock
4353
4354 if (needWake) {
4355 mLooper->wake();
4356 }
4357}
4358
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004359bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 return mInputFilterEnabled;
4361}
4362
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004363void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004364 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004365 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004366 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004367 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004368 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4369 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004370 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4371 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4372 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4373 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4374 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004375 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004376 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4377 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004378 i, args.pointerProperties[i].id,
4379 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4380 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4381 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4382 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4383 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4384 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4385 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4386 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4387 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4388 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004391
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004392 Result<void> motionCheck =
4393 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4394 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004395 if (!motionCheck.ok()) {
4396 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4397 return;
4398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004400 if (DEBUG_VERIFY_EVENTS) {
4401 auto [it, _] =
4402 mVerifiersByDisplay.try_emplace(args.displayId,
4403 StringPrintf("display %" PRId32, args.displayId));
4404 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004405 it->second.processMovement(args.deviceId, args.source, args.action,
4406 args.getPointerCount(), args.pointerProperties.data(),
4407 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004408 if (!result.ok()) {
4409 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4410 }
4411 }
4412
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004413 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004415
4416 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004417 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004418 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4419 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422
Antonio Kantekf16f2832021-09-28 04:39:20 +00004423 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 { // acquire lock
4425 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004426 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4427 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4428 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004429 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004430 if (touchStateIt != mTouchStatesByDisplay.end()) {
4431 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004432 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004433 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4434 }
4435 }
4436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
4438 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004439 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004440 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004441 displayTransform = it->second.transform;
4442 }
4443
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 mLock.unlock();
4445
4446 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004447 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4448 args.action, args.actionButton, args.flags, args.edgeFlags,
4449 args.metaState, args.buttonState, args.classification,
4450 displayTransform, args.xPrecision, args.yPrecision,
4451 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004452 args.downTime, args.eventTime, args.getPointerCount(),
4453 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454
4455 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004456 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 return; // event was consumed by the filter
4458 }
4459
4460 mLock.lock();
4461 }
4462
4463 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004464 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4466 args.displayId, policyFlags, args.action,
4467 args.actionButton, args.flags, args.metaState,
4468 args.buttonState, args.classification, args.edgeFlags,
4469 args.xPrecision, args.yPrecision,
4470 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004471 args.downTime, args.pointerProperties,
4472 args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004474 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4475 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004476 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004477 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004478 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4479 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4480 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004481 }
4482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004483 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 mLock.unlock();
4485 } // release lock
4486
4487 if (needWake) {
4488 mLooper->wake();
4489 }
4490}
4491
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004493 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004494 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4495 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004496 args.id, args.eventTime, args.deviceId, args.source,
4497 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004498 }
Chris Yef59a2f42020-10-16 12:55:26 -07004499
Antonio Kantekf16f2832021-09-28 04:39:20 +00004500 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004501 { // acquire lock
4502 mLock.lock();
4503
4504 // Just enqueue a new sensor event.
4505 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004506 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4507 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4508 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004509
4510 needWake = enqueueInboundEventLocked(std::move(newEntry));
4511 mLock.unlock();
4512 } // release lock
4513
4514 if (needWake) {
4515 mLooper->wake();
4516 }
4517}
4518
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004519void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004520 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004521 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4522 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004523 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004524 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004525}
4526
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004527bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004528 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529}
4530
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004531void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004532 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004533 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4534 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004535 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004538 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004540 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541}
4542
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004543void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004544 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004545 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4546 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548
Antonio Kantekf16f2832021-09-28 04:39:20 +00004549 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004551 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004553 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004554 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004555 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004556
4557 for (auto& [_, verifier] : mVerifiersByDisplay) {
4558 verifier.resetDevice(args.deviceId);
4559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 } // release lock
4561
4562 if (needWake) {
4563 mLooper->wake();
4564 }
4565}
4566
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004567void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004568 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004569 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4570 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004571 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004572
Antonio Kantekf16f2832021-09-28 04:39:20 +00004573 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004574 { // acquire lock
4575 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576 auto entry =
4577 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004578 needWake = enqueueInboundEventLocked(std::move(entry));
4579 } // release lock
4580
4581 if (needWake) {
4582 mLooper->wake();
4583 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004584}
4585
Prabir Pradhan5735a322022-04-11 17:23:34 +00004586InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004587 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004588 InputEventInjectionSync syncMode,
4589 std::chrono::milliseconds timeout,
4590 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004591 Result<void> eventValidation = validateInputEvent(*event);
4592 if (!eventValidation.ok()) {
4593 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4594 return InputEventInjectionResult::FAILED;
4595 }
4596
Prabir Pradhan65613802023-02-22 23:36:58 +00004597 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004598 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4599 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4600 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4601 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004602 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004603 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604
Prabir Pradhan5735a322022-04-11 17:23:34 +00004605 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004607 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004608 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4609 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4610 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4611 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4612 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004613 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004614 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004615 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004616 }
4617
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004618 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004620 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004621 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004622 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004623 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004624 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4625 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4626 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004627 int32_t keyCode = incomingKey.getKeyCode();
4628 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004629 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004630 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004631 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4632 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4633 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004635 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4636 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004637 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638
4639 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4640 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004641 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004642 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4643 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4644 std::to_string(t.duration().count()).c_str());
4645 }
4646 }
4647
4648 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004649 std::unique_ptr<KeyEntry> injectedEntry =
4650 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004652 incomingKey.getDisplayId(), policyFlags, action,
4653 flags, keyCode, incomingKey.getScanCode(), metaState,
4654 incomingKey.getRepeatCount(),
4655 incomingKey.getDownTime());
4656 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004657 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 }
4659
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004660 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004661 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004662 const bool isPointerEvent =
4663 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4664 // If a pointer event has no displayId specified, inject it to the default display.
4665 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4666 ? ADISPLAY_ID_DEFAULT
4667 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004668 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004669
4670 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004671 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004672 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004673 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004674 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4675 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4676 std::to_string(t.duration().count()).c_str());
4677 }
4678 }
4679
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004680 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4681 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4682 }
4683
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004685 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004686 const size_t pointerCount = motionEvent.getPointerCount();
4687 const std::vector<PointerProperties>
4688 pointerProperties(motionEvent.getPointerProperties(),
4689 motionEvent.getPointerProperties() + pointerCount);
4690
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004691 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004692 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004693 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4694 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004695 displayId, policyFlags, motionEvent.getAction(),
4696 motionEvent.getActionButton(), flags,
4697 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004698 motionEvent.getButtonState(),
4699 motionEvent.getClassification(),
4700 motionEvent.getEdgeFlags(),
4701 motionEvent.getXPrecision(),
4702 motionEvent.getYPrecision(),
4703 motionEvent.getRawXCursorPosition(),
4704 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004705 motionEvent.getDownTime(), pointerProperties,
4706 std::vector<PointerCoords>(samplePointerCoords,
4707 samplePointerCoords +
4708 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004709 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004710 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004711 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004712 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004713 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004714 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
4715 MotionEntry>(motionEvent.getId(), *sampleEventTimes, resolvedDeviceId,
4716 motionEvent.getSource(), displayId, policyFlags,
4717 motionEvent.getAction(), motionEvent.getActionButton(), flags,
4718 motionEvent.getMetaState(), motionEvent.getButtonState(),
4719 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4720 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4721 motionEvent.getRawXCursorPosition(),
4722 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4723 pointerProperties,
4724 std::vector<PointerCoords>(samplePointerCoords,
4725 samplePointerCoords +
4726 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004727 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4728 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004729 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 }
4731 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004735 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004736 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
4738
Prabir Pradhan5735a322022-04-11 17:23:34 +00004739 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004740 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 injectionState->injectionIsAsync = true;
4742 }
4743
4744 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004745 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746
4747 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004748 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004749 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004750 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004751 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004752 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004753 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 }
4755
4756 mLock.unlock();
4757
4758 if (needWake) {
4759 mLooper->wake();
4760 }
4761
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004762 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004764 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004766 if (syncMode == InputEventInjectionSync::NONE) {
4767 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 } else {
4769 for (;;) {
4770 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004771 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 break;
4773 }
4774
4775 nsecs_t remainingTimeout = endTime - now();
4776 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004777 if (DEBUG_INJECTION) {
4778 ALOGD("injectInputEvent - Timed out waiting for injection result "
4779 "to become available.");
4780 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004781 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 break;
4783 }
4784
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004785 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 }
4787
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4789 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004791 if (DEBUG_INJECTION) {
4792 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4793 injectionState->pendingForegroundDispatches);
4794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 nsecs_t remainingTimeout = endTime - now();
4796 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004797 if (DEBUG_INJECTION) {
4798 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4799 "dispatches to finish.");
4800 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004801 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 break;
4803 }
4804
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004805 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 }
4807 }
4808 }
4809
4810 injectionState->release();
4811 } // release lock
4812
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004813 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004814 LOG(INFO) << "injectInputEvent - Finished with result "
4815 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817
4818 return injectionResult;
4819}
4820
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004821std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004822 std::array<uint8_t, 32> calculatedHmac;
4823 std::unique_ptr<VerifiedInputEvent> result;
4824 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004825 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004826 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4827 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4828 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004829 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004830 break;
4831 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004832 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004833 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4834 VerifiedMotionEvent verifiedMotionEvent =
4835 verifiedMotionEventFromMotionEvent(motionEvent);
4836 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004837 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004838 break;
4839 }
4840 default: {
4841 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4842 return nullptr;
4843 }
4844 }
4845 if (calculatedHmac == INVALID_HMAC) {
4846 return nullptr;
4847 }
tyiu1573a672023-02-21 22:38:32 +00004848 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004849 return nullptr;
4850 }
4851 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004852}
4853
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004854void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004855 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004856 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004858 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004859 LOG(INFO) << "Setting input event injection result to "
4860 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004863 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 // Log the outcome since the injector did not wait for the injection result.
4865 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004866 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004867 ALOGV("Asynchronous input event injection succeeded.");
4868 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004869 case InputEventInjectionResult::TARGET_MISMATCH:
4870 ALOGV("Asynchronous input event injection target mismatch.");
4871 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004872 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004873 ALOGW("Asynchronous input event injection failed.");
4874 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004875 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876 ALOGW("Asynchronous input event injection timed out.");
4877 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004878 case InputEventInjectionResult::PENDING:
4879 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4880 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 }
4882 }
4883
4884 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004885 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 }
4887}
4888
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004889void InputDispatcher::transformMotionEntryForInjectionLocked(
4890 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004891 // Input injection works in the logical display coordinate space, but the input pipeline works
4892 // display space, so we need to transform the injected events accordingly.
4893 const auto it = mDisplayInfos.find(entry.displayId);
4894 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004895 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004896
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004897 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4898 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4899 const vec2 cursor =
4900 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4901 {entry.xCursorPosition, entry.yCursorPosition});
4902 entry.xCursorPosition = cursor.x;
4903 entry.yCursorPosition = cursor.y;
4904 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004905 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004906 entry.pointerCoords[i] =
4907 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4908 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004909 }
4910}
4911
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004912void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4913 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 if (injectionState) {
4915 injectionState->pendingForegroundDispatches += 1;
4916 }
4917}
4918
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004919void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4920 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 if (injectionState) {
4922 injectionState->pendingForegroundDispatches -= 1;
4923
4924 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004925 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 }
4927 }
4928}
4929
chaviw98318de2021-05-19 16:45:23 -05004930const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004931 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004932 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004933 auto it = mWindowHandlesByDisplay.find(displayId);
4934 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004935}
4936
chaviw98318de2021-05-19 16:45:23 -05004937sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004938 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004939 if (windowHandleToken == nullptr) {
4940 return nullptr;
4941 }
4942
Prabir Pradhan16463382023-10-12 23:03:19 +00004943 if (!displayId) {
4944 // Look through all displays.
4945 for (auto& it : mWindowHandlesByDisplay) {
4946 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4947 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4948 if (windowHandle->getToken() == windowHandleToken) {
4949 return windowHandle;
4950 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004953 return nullptr;
4954 }
4955
Prabir Pradhan16463382023-10-12 23:03:19 +00004956 // Only look through the requested display.
4957 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004958 if (windowHandle->getToken() == windowHandleToken) {
4959 return windowHandle;
4960 }
4961 }
4962 return nullptr;
4963}
4964
chaviw98318de2021-05-19 16:45:23 -05004965sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4966 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004967 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004968 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4969 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004970 if (handle->getId() == windowHandle->getId() &&
4971 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004972 if (windowHandle->getInfo()->displayId != it.first) {
4973 ALOGE("Found window %s in display %" PRId32
4974 ", but it should belong to display %" PRId32,
4975 windowHandle->getName().c_str(), it.first,
4976 windowHandle->getInfo()->displayId);
4977 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004978 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 }
4981 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004982 return nullptr;
4983}
4984
chaviw98318de2021-05-19 16:45:23 -05004985sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004986 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4987 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988}
4989
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004990ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4991 auto displayInfoIt = mDisplayInfos.find(displayId);
4992 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4993 : kIdentityTransform;
4994}
4995
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004996bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4997 const MotionEntry& motionEntry) const {
4998 const WindowInfo& info = *window->getInfo();
4999
5000 // Skip spy window targets that are not valid for targeted injection.
5001 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005002 return false;
5003 }
5004
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005005 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5006 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5007 return false;
5008 }
5009
5010 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5011 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5012 window->getName().c_str());
5013 return false;
5014 }
5015
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005016 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005017 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005018 ALOGW("Not sending touch to %s because there's no corresponding connection",
5019 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005020 return false;
5021 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005022
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005023 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005024 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005025 return false;
5026 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005027
5028 // Drop events that can't be trusted due to occlusion
5029 const auto [x, y] = resolveTouchedPosition(motionEntry);
5030 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5031 if (!isTouchTrustedLocked(occlusionInfo)) {
5032 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005033 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005034 for (const auto& log : occlusionInfo.debugInfo) {
5035 ALOGD("%s", log.c_str());
5036 }
5037 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005038 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5039 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005040 return false;
5041 }
5042
5043 // Drop touch events if requested by input feature
5044 if (shouldDropInput(motionEntry, window)) {
5045 return false;
5046 }
5047
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005048 return true;
5049}
5050
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005051std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5052 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005053 auto connectionIt = mConnectionsByToken.find(token);
5054 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005055 return nullptr;
5056 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005057 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005058}
5059
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005060void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005061 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5062 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005063 // Remove all handles on a display if there are no windows left.
5064 mWindowHandlesByDisplay.erase(displayId);
5065 return;
5066 }
5067
5068 // Since we compare the pointer of input window handles across window updates, we need
5069 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005070 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5071 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5072 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005073 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005074 }
5075
chaviw98318de2021-05-19 16:45:23 -05005076 std::vector<sp<WindowInfoHandle>> newHandles;
5077 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005078 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005079 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005080 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005081 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005082 const bool canReceiveInput =
5083 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5084 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005085 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005086 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005087 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005088 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005089 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005090 }
5091
5092 if (info->displayId != displayId) {
5093 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5094 handle->getName().c_str(), displayId, info->displayId);
5095 continue;
5096 }
5097
Robert Carredd13602020-04-13 17:24:34 -07005098 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5099 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005100 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005101 oldHandle->updateFrom(handle);
5102 newHandles.push_back(oldHandle);
5103 } else {
5104 newHandles.push_back(handle);
5105 }
5106 }
5107
5108 // Insert or replace
5109 mWindowHandlesByDisplay[displayId] = newHandles;
5110}
5111
Arthur Hungb92218b2018-08-14 12:00:21 +08005112/**
5113 * Called from InputManagerService, update window handle list by displayId that can receive input.
5114 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5115 * If set an empty list, remove all handles from the specific display.
5116 * For focused handle, check if need to change and send a cancel event to previous one.
5117 * For removed handle, check if need to send a cancel event if already in touch.
5118 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005119void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005120 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005121 if (DEBUG_FOCUS) {
5122 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005123 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005124 windowList += iwh->getName() + " ";
5125 }
5126 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128
Prabir Pradhand65552b2021-10-07 11:23:50 -07005129 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005130 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005131 const WindowInfo& info = *window->getInfo();
5132
5133 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005134 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005135 if (noInputWindow && window->getToken() != nullptr) {
5136 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5137 window->getName().c_str());
5138 window->releaseChannel();
5139 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005140
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005141 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005142 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5143 !info.inputConfig.test(
5144 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005145 "%s has feature SPY, but is not a trusted overlay.",
5146 window->getName().c_str());
5147
Prabir Pradhand65552b2021-10-07 11:23:50 -07005148 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005149 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5150 !info.inputConfig.test(
5151 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005152 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5153 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005154 }
5155
Arthur Hung72d8dc32020-03-28 00:48:39 +00005156 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005157 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
chaviw98318de2021-05-19 16:45:23 -05005159 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005160
chaviw98318de2021-05-19 16:45:23 -05005161 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005162
Vishnu Nairc519ff72021-01-21 08:23:08 -08005163 std::optional<FocusResolver::FocusChanges> changes =
5164 mFocusResolver.setInputWindows(displayId, windowHandles);
5165 if (changes) {
5166 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005169 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5170 mTouchStatesByDisplay.find(displayId);
5171 if (stateIt != mTouchStatesByDisplay.end()) {
5172 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005173 for (size_t i = 0; i < state.windows.size();) {
5174 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005175 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005176 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5177 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005178 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005179 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5180 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005181 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005182 "touched window was removed");
5183 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005184 // Since we are about to drop the touch, cancel the events for the wallpaper as
5185 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005186 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005187 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5188 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005189 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005190 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005193 state.windows.erase(state.windows.begin() + i);
5194 } else {
5195 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 }
5197 }
arthurhungb89ccb02020-12-30 16:19:01 +08005198
arthurhung6d4bed92021-03-17 11:59:33 +08005199 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005200 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005201 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005202 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005203 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005204 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5205 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005206 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005207 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005208 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005209
Arthur Hung72d8dc32020-03-28 00:48:39 +00005210 // Release information for windows that are no longer present.
5211 // This ensures that unused input channels are released promptly.
5212 // Otherwise, they might stick around until the window handle is destroyed
5213 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005214 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005215 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005216 if (DEBUG_FOCUS) {
5217 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005218 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005219 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005220 }
chaviw291d88a2019-02-14 10:33:58 -08005221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222}
5223
5224void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005225 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005226 if (DEBUG_FOCUS) {
5227 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5228 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5229 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005230 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005231 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005232 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 } // release lock
5234
5235 // Wake up poll loop since it may need to make new input dispatching choices.
5236 mLooper->wake();
5237}
5238
Vishnu Nair599f1412021-06-21 10:39:58 -07005239void InputDispatcher::setFocusedApplicationLocked(
5240 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5241 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5242 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5243
5244 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5245 return; // This application is already focused. No need to wake up or change anything.
5246 }
5247
5248 // Set the new application handle.
5249 if (inputApplicationHandle != nullptr) {
5250 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5251 } else {
5252 mFocusedApplicationHandlesByDisplay.erase(displayId);
5253 }
5254
5255 // No matter what the old focused application was, stop waiting on it because it is
5256 // no longer focused.
5257 resetNoFocusedWindowTimeoutLocked();
5258}
5259
Tiger Huang721e26f2018-07-24 22:26:19 +08005260/**
5261 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5262 * the display not specified.
5263 *
5264 * We track any unreleased events for each window. If a window loses the ability to receive the
5265 * released event, we will send a cancel event to it. So when the focused display is changed, we
5266 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5267 * display. The display-specified events won't be affected.
5268 */
5269void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005270 if (DEBUG_FOCUS) {
5271 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5272 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005273 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005274 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005275
5276 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005277 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005278 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005279 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005280 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005281 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005282 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005283 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005284 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005285 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005286 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005287 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5288 }
5289 }
5290 mFocusedDisplayId = displayId;
5291
Chris Ye3c2d6f52020-08-09 10:39:48 -07005292 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005293 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005294 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005295
Vishnu Nairad321cd2020-08-20 16:40:21 -07005296 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005297 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005298 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005299 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005300 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005301 }
5302 }
5303 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005304 } // release lock
5305
5306 // Wake up poll loop since it may need to make new input dispatching choices.
5307 mLooper->wake();
5308}
5309
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005311 if (DEBUG_FOCUS) {
5312 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314
5315 bool changed;
5316 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005317 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318
5319 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5320 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005321 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 }
5323
5324 if (mDispatchEnabled && !enabled) {
5325 resetAndDropEverythingLocked("dispatcher is being disabled");
5326 }
5327
5328 mDispatchEnabled = enabled;
5329 mDispatchFrozen = frozen;
5330 changed = true;
5331 } else {
5332 changed = false;
5333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 } // release lock
5335
5336 if (changed) {
5337 // Wake up poll loop since it may need to make new input dispatching choices.
5338 mLooper->wake();
5339 }
5340}
5341
5342void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005343 if (DEBUG_FOCUS) {
5344 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346
5347 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005348 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349
5350 if (mInputFilterEnabled == enabled) {
5351 return;
5352 }
5353
5354 mInputFilterEnabled = enabled;
5355 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5356 } // release lock
5357
5358 // Wake up poll loop since there might be work to do to drop everything.
5359 mLooper->wake();
5360}
5361
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005362bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005363 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005364 bool needWake = false;
5365 {
5366 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005367 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005368 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005369 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005370 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5371 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005372 mTouchModePerDisplay.count(displayId) == 0
5373 ? "not set"
5374 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5375
Antonio Kantek15beb512022-06-13 22:35:41 +00005376 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5377 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005378 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005379 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005380 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005381 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5382 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005383 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005384 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005385 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005386 return false;
5387 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005388 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005389 mTouchModePerDisplay[displayId] = inTouchMode;
5390 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5391 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005392 needWake = enqueueInboundEventLocked(std::move(entry));
5393 } // release lock
5394
5395 if (needWake) {
5396 mLooper->wake();
5397 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005398 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005399}
5400
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005401bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005402 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5403 if (focusedToken == nullptr) {
5404 return false;
5405 }
5406 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5407 return isWindowOwnedBy(windowHandle, pid, uid);
5408}
5409
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005410bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005411 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5412 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5413 const sp<WindowInfoHandle> windowHandle =
5414 getWindowHandleLocked(connectionToken);
5415 return isWindowOwnedBy(windowHandle, pid, uid);
5416 }) != mInteractionConnectionTokens.end();
5417}
5418
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005419void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5420 if (opacity < 0 || opacity > 1) {
5421 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5422 return;
5423 }
5424
5425 std::scoped_lock lock(mLock);
5426 mMaximumObscuringOpacityForTouch = opacity;
5427}
5428
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005429std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5430InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005431 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5432 for (TouchedWindow& w : state.windows) {
5433 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005434 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005435 }
5436 }
5437 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005438 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005439}
5440
arthurhungb89ccb02020-12-30 16:19:01 +08005441bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5442 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005443 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005444 if (DEBUG_FOCUS) {
5445 ALOGD("Trivial transfer to same window.");
5446 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005447 return true;
5448 }
5449
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005451 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452
Arthur Hungabbb9d82021-09-01 14:52:30 +00005453 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005454 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005455
Arthur Hungabbb9d82021-09-01 14:52:30 +00005456 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005457 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 return false;
5459 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005460 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5461 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005462 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5463 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005464 return false;
5465 }
5466 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005467
Arthur Hungabbb9d82021-09-01 14:52:30 +00005468 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5469 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005470 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005471 return false;
5472 }
5473
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005474 if (DEBUG_FOCUS) {
5475 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005476 touchedWindow->windowHandle->getName().c_str(),
5477 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479
Arthur Hungabbb9d82021-09-01 14:52:30 +00005480 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005481 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005482 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005483 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005484 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
Arthur Hungabbb9d82021-09-01 14:52:30 +00005486 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005487 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005488 ftl::Flags<InputTarget::Flags> newTargetFlags =
5489 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005490 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005491 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005492 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005493 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5494 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495
Arthur Hungabbb9d82021-09-01 14:52:30 +00005496 // Store the dragging window.
5497 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005498 if (pointerIds.count() != 1) {
5499 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5500 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005501 return false;
5502 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005503 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005504 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005505 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 }
5507
Arthur Hungabbb9d82021-09-01 14:52:30 +00005508 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005509 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5510 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005511 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005512 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005513 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5514 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005516 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5517 newTargetFlags);
5518
5519 // Check if the wallpaper window should deliver the corresponding event.
5520 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005521 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 } // release lock
5524
5525 // Wake up poll loop since it may need to make new input dispatching choices.
5526 mLooper->wake();
5527 return true;
5528}
5529
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005530/**
5531 * Get the touched foreground window on the given display.
5532 * Return null if there are no windows touched on that display, or if more than one foreground
5533 * window is being touched.
5534 */
5535sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5536 auto stateIt = mTouchStatesByDisplay.find(displayId);
5537 if (stateIt == mTouchStatesByDisplay.end()) {
5538 ALOGI("No touch state on display %" PRId32, displayId);
5539 return nullptr;
5540 }
5541
5542 const TouchState& state = stateIt->second;
5543 sp<WindowInfoHandle> touchedForegroundWindow;
5544 // If multiple foreground windows are touched, return nullptr
5545 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005546 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005547 if (touchedForegroundWindow != nullptr) {
5548 ALOGI("Two or more foreground windows: %s and %s",
5549 touchedForegroundWindow->getName().c_str(),
5550 window.windowHandle->getName().c_str());
5551 return nullptr;
5552 }
5553 touchedForegroundWindow = window.windowHandle;
5554 }
5555 }
5556 return touchedForegroundWindow;
5557}
5558
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005559// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005560bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005561 sp<IBinder> fromToken;
5562 { // acquire lock
5563 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005564 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005565 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005566 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5567 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005568 return false;
5569 }
5570
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005571 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5572 if (from == nullptr) {
5573 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5574 return false;
5575 }
5576
5577 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005578 } // release lock
5579
5580 return transferTouchFocus(fromToken, destChannelToken);
5581}
5582
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005584 if (DEBUG_FOCUS) {
5585 ALOGD("Resetting and dropping all events (%s).", reason);
5586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587
Michael Wrightfb04fd52022-11-24 22:31:11 +00005588 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 synthesizeCancelationEventsForAllConnectionsLocked(options);
5590
5591 resetKeyRepeatLocked();
5592 releasePendingEventLocked();
5593 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005594 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005596 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005597 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598}
5599
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005600void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005601 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 dumpDispatchStateLocked(dump);
5603
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005604 std::istringstream stream(dump);
5605 std::string line;
5606
5607 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005608 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 }
5610}
5611
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005612std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005613 std::string dump;
5614
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005615 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5616 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005617
5618 std::string windowName = "None";
5619 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005620 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005621 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5622 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5623 : "token has capture without window";
5624 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005625 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005626
5627 return dump;
5628}
5629
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005630void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005631 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5632 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5633 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005634 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635
Tiger Huang721e26f2018-07-24 22:26:19 +08005636 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5637 dump += StringPrintf(INDENT "FocusedApplications:\n");
5638 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5639 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005640 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005641 const std::chrono::duration timeout =
5642 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005643 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005644 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005645 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005648 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005650
Vishnu Nairc519ff72021-01-21 08:23:08 -08005651 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005652 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005654 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005655 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005656 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005657 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5658 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 }
5660 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005661 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662 }
5663
arthurhung6d4bed92021-03-17 11:59:33 +08005664 if (mDragState) {
5665 dump += StringPrintf(INDENT "DragState:\n");
5666 mDragState->dump(dump, INDENT2);
5667 }
5668
Arthur Hungb92218b2018-08-14 12:00:21 +08005669 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005670 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5671 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5672 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5673 const auto& displayInfo = it->second;
5674 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5675 displayInfo.logicalHeight);
5676 displayInfo.transform.dump(dump, "transform", INDENT4);
5677 } else {
5678 dump += INDENT2 "No DisplayInfo found!\n";
5679 }
5680
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005681 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005682 dump += INDENT2 "Windows:\n";
5683 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005684 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5685 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005687 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005688 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005689 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005690 "applicationInfo.name=%s, "
5691 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005692 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005693 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005694 windowInfo->displayId,
5695 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005696 windowInfo->alpha, windowInfo->frame.left,
5697 windowInfo->frame.top, windowInfo->frame.right,
5698 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005699 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005700 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005701 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005702 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005703 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005704 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005705 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005706 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005707 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005708 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005709 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005710 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005711 }
5712 } else {
5713 dump += INDENT2 "Windows: <none>\n";
5714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005717 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005720 if (!mGlobalMonitorsByDisplay.empty()) {
5721 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5722 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005723 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005726 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 }
5728
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005729 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730
5731 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005732 if (!mRecentQueue.empty()) {
5733 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005734 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005735 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005736 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005737 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005740 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
5743 // Dump event currently being dispatched.
5744 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005745 dump += INDENT "PendingEvent:\n";
5746 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005747 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005748 dump += StringPrintf(", age=%" PRId64 "ms\n",
5749 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005751 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 }
5753
5754 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005755 if (!mInboundQueue.empty()) {
5756 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005757 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005758 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005759 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005760 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761 }
5762 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005763 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 }
5765
Prabir Pradhancef936d2021-07-21 16:17:52 +00005766 if (!mCommandQueue.empty()) {
5767 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5768 } else {
5769 dump += INDENT "CommandQueue: <empty>\n";
5770 }
5771
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005772 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005773 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005774 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005775 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005776 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005777 connection->inputChannel->getFd().get(),
5778 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005779 connection->getWindowName().c_str(),
5780 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005781 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005783 if (!connection->outboundQueue.empty()) {
5784 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5785 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005786 dump += dumpQueue(connection->outboundQueue, currentTime);
5787
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005789 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 }
5791
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005792 if (!connection->waitQueue.empty()) {
5793 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5794 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005795 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005797 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005799 std::stringstream inputStateDump;
5800 inputStateDump << connection->inputState;
5801 if (!isEmpty(inputStateDump)) {
5802 dump += INDENT3 "InputState: ";
5803 dump += inputStateDump.str() + "\n";
5804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 }
5806 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005807 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 }
5809
5810 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005811 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5812 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005814 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 }
5816
Antonio Kantek15beb512022-06-13 22:35:41 +00005817 if (!mTouchModePerDisplay.empty()) {
5818 dump += INDENT "TouchModePerDisplay:\n";
5819 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5820 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5821 std::to_string(touchMode).c_str());
5822 }
5823 } else {
5824 dump += INDENT "TouchModePerDisplay: <none>\n";
5825 }
5826
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005828 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5829 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5830 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005831 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005832 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833}
5834
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005835void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005836 const size_t numMonitors = monitors.size();
5837 for (size_t i = 0; i < numMonitors; i++) {
5838 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005839 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005840 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5841 dump += "\n";
5842 }
5843}
5844
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005845class LooperEventCallback : public LooperCallback {
5846public:
5847 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5848 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5849
5850private:
5851 std::function<int(int events)> mCallback;
5852};
5853
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005854Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005855 if (DEBUG_CHANNEL_CREATION) {
5856 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005859 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005860 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005861 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005862
5863 if (result) {
5864 return base::Error(result) << "Failed to open input channel pair with name " << name;
5865 }
5866
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005868 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005869 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005870 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005871 std::shared_ptr<Connection> connection =
5872 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5873 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005875 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5876 ALOGE("Created a new connection, but the token %p is already known", token.get());
5877 }
5878 mConnectionsByToken.emplace(token, connection);
5879
5880 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5881 this, std::placeholders::_1, token);
5882
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005883 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5884 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 } // release lock
5886
5887 // Wake the looper because some connections have changed.
5888 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005889 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890}
5891
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005892Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005893 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005894 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005895 std::shared_ptr<InputChannel> serverChannel;
5896 std::unique_ptr<InputChannel> clientChannel;
5897 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5898 if (result) {
5899 return base::Error(result) << "Failed to open input channel pair with name " << name;
5900 }
5901
Michael Wright3dd60e22019-03-27 22:06:44 +00005902 { // acquire lock
5903 std::scoped_lock _l(mLock);
5904
5905 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005906 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5907 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005908 }
5909
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005910 std::shared_ptr<Connection> connection =
5911 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005912 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005913 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005914
5915 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5916 ALOGE("Created a new connection, but the token %p is already known", token.get());
5917 }
5918 mConnectionsByToken.emplace(token, connection);
5919 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5920 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005921
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005922 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005923
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005924 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5925 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005926 }
Garfield Tan15601662020-09-22 15:32:38 -07005927
Michael Wright3dd60e22019-03-27 22:06:44 +00005928 // Wake the looper because some connections have changed.
5929 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005930 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005931}
5932
Garfield Tan15601662020-09-22 15:32:38 -07005933status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936
Harry Cutts33476232023-01-30 19:57:29 +00005937 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 if (status) {
5939 return status;
5940 }
5941 } // release lock
5942
5943 // Wake the poll loop because removing the connection may have changed the current
5944 // synchronization state.
5945 mLooper->wake();
5946 return OK;
5947}
5948
Garfield Tan15601662020-09-22 15:32:38 -07005949status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5950 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005951 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005952 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005953 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 return BAD_VALUE;
5955 }
5956
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005957 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005958
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005960 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
5962
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005963 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964
5965 nsecs_t currentTime = now();
5966 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5967
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005968 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969 return OK;
5970}
5971
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005972void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005973 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5974 auto& [displayId, monitors] = *it;
5975 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5976 return monitor.inputChannel->getConnectionToken() == connectionToken;
5977 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005978
Michael Wright3dd60e22019-03-27 22:06:44 +00005979 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005980 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005981 } else {
5982 ++it;
5983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984 }
5985}
5986
Michael Wright3dd60e22019-03-27 22:06:44 +00005987status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005988 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005989 return pilferPointersLocked(token);
5990}
Michael Wright3dd60e22019-03-27 22:06:44 +00005991
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005992status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005993 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5994 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005995 LOG(WARNING)
5996 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005997 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005998 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005999
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006000 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006001 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006002 LOG(WARNING)
6003 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6004 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006005 return BAD_VALUE;
6006 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006007 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006008 if (deviceIds.empty()) {
6009 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006010 return BAD_VALUE;
6011 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006012
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006013 for (const DeviceId deviceId : deviceIds) {
6014 TouchState& state = *statePtr;
6015 TouchedWindow& window = *windowPtr;
6016 // Send cancel events to all the input channels we're stealing from.
6017 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6018 "input channel stole pointer stream");
6019 options.deviceId = deviceId;
6020 options.displayId = displayId;
6021 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6022 options.pointerIds = pointerIds;
6023 std::string canceledWindows;
6024 for (const TouchedWindow& w : state.windows) {
6025 const std::shared_ptr<InputChannel> channel =
6026 getInputChannelLocked(w.windowHandle->getToken());
6027 if (channel != nullptr && channel->getConnectionToken() != token) {
6028 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6029 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6030 canceledWindows += channel->getName();
6031 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006032 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006033 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6034 LOG(INFO) << "Channel " << requestingChannel->getName()
6035 << " is stealing input gesture for device " << deviceId << " from "
6036 << canceledWindows;
6037
6038 // Prevent the gesture from being sent to any other windows.
6039 // This only blocks relevant pointers to be sent to other windows
6040 window.addPilferingPointers(deviceId, pointerIds);
6041
6042 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006043 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006044 return OK;
6045}
6046
Prabir Pradhan99987712020-11-10 18:43:05 -08006047void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6048 { // acquire lock
6049 std::scoped_lock _l(mLock);
6050 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006051 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006052 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6053 windowHandle != nullptr ? windowHandle->getName().c_str()
6054 : "token without window");
6055 }
6056
Vishnu Nairc519ff72021-01-21 08:23:08 -08006057 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006058 if (focusedToken != windowToken) {
6059 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6060 enabled ? "enable" : "disable");
6061 return;
6062 }
6063
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006064 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006065 ALOGW("Ignoring request to %s Pointer Capture: "
6066 "window has %s requested pointer capture.",
6067 enabled ? "enable" : "disable", enabled ? "already" : "not");
6068 return;
6069 }
6070
Christine Franksb768bb42021-11-29 12:11:31 -08006071 if (enabled) {
6072 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6073 mIneligibleDisplaysForPointerCapture.end(),
6074 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6075 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6076 return;
6077 }
6078 }
6079
Prabir Pradhan99987712020-11-10 18:43:05 -08006080 setPointerCaptureLocked(enabled);
6081 } // release lock
6082
6083 // Wake the thread to process command entries.
6084 mLooper->wake();
6085}
6086
Christine Franksb768bb42021-11-29 12:11:31 -08006087void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6088 { // acquire lock
6089 std::scoped_lock _l(mLock);
6090 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6091 if (!isEligible) {
6092 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6093 }
6094 } // release lock
6095}
6096
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006097std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006098 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006099 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006100 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006101 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006102 }
6103 }
6104 }
6105 return std::nullopt;
6106}
6107
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006108std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6109 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006110 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006111 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006112 }
6113
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006114 for (const auto& [token, connection] : mConnectionsByToken) {
6115 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006116 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 }
6118 }
Robert Carr4e670e52018-08-15 13:26:12 -07006119
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006120 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121}
6122
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006123std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006124 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006125 if (connection == nullptr) {
6126 return "<nullptr>";
6127 }
6128 return connection->getInputChannelName();
6129}
6130
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006131void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006132 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006133 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006134}
6135
Prabir Pradhancef936d2021-07-21 16:17:52 +00006136void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006137 const std::shared_ptr<Connection>& connection,
6138 uint32_t seq, bool handled,
6139 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006140 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006141 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006142
6143 { // Start critical section
6144 auto dispatchEntryIt =
6145 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6146 [seq](auto& e) { return e->seq == seq; });
6147 if (dispatchEntryIt == connection->waitQueue.end()) {
6148 return;
6149 }
6150
6151 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6152
6153 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6154 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6155 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6156 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6157 }
6158 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6159 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6160 connection->inputChannel->getConnectionToken(),
6161 dispatchEntry.deliveryTime, consumeTime, finishTime);
6162 }
6163
6164 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6165 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6166 restartEvent =
6167 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6168 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6169 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6170 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6171 motionEntry, handled);
6172 } else {
6173 restartEvent = false;
6174 }
6175 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006176
6177 // Dequeue the event and start the next cycle.
6178 // Because the lock might have been released, it is possible that the
6179 // contents of the wait queue to have been drained, so we need to double-check
6180 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006181 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6182 [seq](auto& e) { return e->seq == seq; });
6183 if (entryIt != connection->waitQueue.end()) {
6184 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6185 connection->waitQueue.erase(entryIt);
6186
Prabir Pradhancef936d2021-07-21 16:17:52 +00006187 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6188 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6189 if (!connection->responsive) {
6190 connection->responsive = isConnectionResponsive(*connection);
6191 if (connection->responsive) {
6192 // The connection was unresponsive, and now it's responsive.
6193 processConnectionResponsiveLocked(*connection);
6194 }
6195 }
6196 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006197 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006198 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006199 traceOutboundQueueLength(*connection);
6200 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006201 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006202 }
6203 }
6204
6205 // Start the next dispatch cycle for this connection.
6206 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207}
6208
Prabir Pradhancef936d2021-07-21 16:17:52 +00006209void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6210 const sp<IBinder>& newToken) {
6211 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6212 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006213 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006214 };
6215 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216}
6217
Prabir Pradhancef936d2021-07-21 16:17:52 +00006218void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6219 auto command = [this, token, x, y]() REQUIRES(mLock) {
6220 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006221 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006222 };
6223 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006224}
6225
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006226void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006227 if (connection == nullptr) {
6228 LOG_ALWAYS_FATAL("Caller must check for nullness");
6229 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006230 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6231 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006232 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006233 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006234 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006235 return;
6236 }
6237 /**
6238 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6239 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6240 * has changed. This could cause newer entries to time out before the already dispatched
6241 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6242 * processes the events linearly. So providing information about the oldest entry seems to be
6243 * most useful.
6244 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006245 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6246 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006247 std::string reason =
6248 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006249 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006250 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006251 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006252 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006253 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006254
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006255 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6256
6257 // Stop waking up for events on this connection, it is already unresponsive
6258 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006259}
6260
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006261void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6262 std::string reason =
6263 StringPrintf("%s does not have a focused window", application->getName().c_str());
6264 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006265
Yabin Cui8eb9c552023-06-08 18:05:07 +00006266 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006267 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006268 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006269 };
6270 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006271}
6272
chaviw98318de2021-05-19 16:45:23 -05006273void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006274 const std::string& reason) {
6275 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6276 updateLastAnrStateLocked(windowLabel, reason);
6277}
6278
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006279void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6280 const std::string& reason) {
6281 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006282 updateLastAnrStateLocked(windowLabel, reason);
6283}
6284
6285void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6286 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006288 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289 struct tm tm;
6290 localtime_r(&t, &tm);
6291 char timestr[64];
6292 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006293 mLastAnrState.clear();
6294 mLastAnrState += INDENT "ANR:\n";
6295 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006296 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6297 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006298 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299}
6300
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6302 KeyEntry& entry) {
6303 const KeyEvent event = createKeyEvent(entry);
6304 nsecs_t delay = 0;
6305 { // release lock
6306 scoped_unlock unlock(mLock);
6307 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006308 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006309 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6310 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6311 std::to_string(t.duration().count()).c_str());
6312 }
6313 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314
6315 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006316 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006317 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006318 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006320 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006321 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323}
6324
Prabir Pradhancef936d2021-07-21 16:17:52 +00006325void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006326 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006328 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006329 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006330 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331 };
6332 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006333}
6334
Prabir Pradhanedd96402022-02-15 01:46:16 -08006335void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006336 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006337 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006338 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006339 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006340 };
6341 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006342}
6343
6344/**
6345 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6346 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6347 * command entry to the command queue.
6348 */
6349void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6350 std::string reason) {
6351 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006352 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006353 if (connection.monitor) {
6354 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6355 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006356 pid = findMonitorPidByTokenLocked(connectionToken);
6357 } else {
6358 // The connection is a window
6359 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6360 reason.c_str());
6361 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6362 if (handle != nullptr) {
6363 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006364 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006365 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006366 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006367}
6368
6369/**
6370 * Tell the policy that a connection has become responsive so that it can stop ANR.
6371 */
6372void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6373 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006374 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006375 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006376 pid = findMonitorPidByTokenLocked(connectionToken);
6377 } else {
6378 // The connection is a window
6379 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6380 if (handle != nullptr) {
6381 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006382 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006383 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006384 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006385}
6386
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006387bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006388 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006389 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006390 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006391 if (!handled) {
6392 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006393 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006394 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006395 return false;
6396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006398 // Get the fallback key state.
6399 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006400 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006401 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006402 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006403 connection->inputState.removeFallbackKey(originalKeyCode);
6404 }
6405
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006406 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006407 // If the application handles the original key for which we previously
6408 // generated a fallback or if the window is not a foreground window,
6409 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006410 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006411 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006412 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6413 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6414 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6415 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6416 keyEntry.policyFlags);
6417 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006418 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006420
6421 mLock.unlock();
6422
Prabir Pradhana41d2442023-04-20 21:30:40 +00006423 if (const auto unhandledKeyFallback =
6424 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6425 event, keyEntry.policyFlags);
6426 unhandledKeyFallback) {
6427 event = *unhandledKeyFallback;
6428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006429
6430 mLock.lock();
6431
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006433 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006434 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006435 "application handled the original non-fallback key "
6436 "or is no longer a foreground target, "
6437 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006438 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006439 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 connection->inputState.removeFallbackKey(originalKeyCode);
6442 }
6443 } else {
6444 // If the application did not handle a non-fallback key, first check
6445 // that we are in a good state to perform unhandled key event processing
6446 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006447 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006448 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006449 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6450 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6451 "since this is not an initial down. "
6452 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6453 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6454 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 return false;
6456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006457
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006458 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006459 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6460 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6461 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6462 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6463 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006464 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006465
6466 mLock.unlock();
6467
Prabir Pradhana41d2442023-04-20 21:30:40 +00006468 bool fallback = false;
6469 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6470 event, keyEntry.policyFlags);
6471 fb) {
6472 fallback = true;
6473 event = *fb;
6474 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006475
6476 mLock.lock();
6477
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006478 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479 connection->inputState.removeFallbackKey(originalKeyCode);
6480 return false;
6481 }
6482
6483 // Latch the fallback keycode for this key on an initial down.
6484 // The fallback keycode cannot change at any other point in the lifecycle.
6485 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006486 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006487 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006489 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006491 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006492 }
6493
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006495
6496 // Cancel the fallback key if the policy decides not to send it anymore.
6497 // We will continue to dispatch the key to the policy but we will no
6498 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006499 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6500 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006501 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6502 if (fallback) {
6503 ALOGD("Unhandled key event: Policy requested to send key %d"
6504 "as a fallback for %d, but on the DOWN it had requested "
6505 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 } else {
6508 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6509 "but on the DOWN it had requested to send %d. "
6510 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006511 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006512 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006514
Michael Wrightfb04fd52022-11-24 22:31:11 +00006515 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006516 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006517 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006518 synthesizeCancelationEventsForConnectionLocked(connection, options);
6519
6520 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006521 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006522 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006523 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 }
6525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6528 {
6529 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006530 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006531 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 for (const auto& [key, value] : fallbackKeys) {
6533 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006534 }
6535 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6536 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006539
6540 if (fallback) {
6541 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006542 keyEntry.eventTime = event.getEventTime();
6543 keyEntry.deviceId = event.getDeviceId();
6544 keyEntry.source = event.getSource();
6545 keyEntry.displayId = event.getDisplayId();
6546 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006547 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006548 keyEntry.scanCode = event.getScanCode();
6549 keyEntry.metaState = event.getMetaState();
6550 keyEntry.repeatCount = event.getRepeatCount();
6551 keyEntry.downTime = event.getDownTime();
6552 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006553
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006554 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6555 ALOGD("Unhandled key event: Dispatching fallback key. "
6556 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006557 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006558 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006559 return true; // restart the event
6560 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006561 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6562 ALOGD("Unhandled key event: No fallback key.");
6563 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006564
6565 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006566 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567 }
6568 }
6569 return false;
6570}
6571
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006572bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006573 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006574 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575 return false;
6576}
6577
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578void InputDispatcher::traceInboundQueueLengthLocked() {
6579 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006580 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581 }
6582}
6583
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006584void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585 if (ATRACE_ENABLED()) {
6586 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006587 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6588 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 }
6590}
6591
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006592void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593 if (ATRACE_ENABLED()) {
6594 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006595 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6596 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597 }
6598}
6599
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006600void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006601 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006602
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006603 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 dumpDispatchStateLocked(dump);
6605
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006606 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006607 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006608 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609 }
6610}
6611
6612void InputDispatcher::monitor() {
6613 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006614 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006616 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617}
6618
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006619/**
6620 * Wake up the dispatcher and wait until it processes all events and commands.
6621 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6622 * this method can be safely called from any thread, as long as you've ensured that
6623 * the work you are interested in completing has already been queued.
6624 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006625bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006626 /**
6627 * Timeout should represent the longest possible time that a device might spend processing
6628 * events and commands.
6629 */
6630 constexpr std::chrono::duration TIMEOUT = 100ms;
6631 std::unique_lock lock(mLock);
6632 mLooper->wake();
6633 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6634 return result == std::cv_status::no_timeout;
6635}
6636
Vishnu Naire798b472020-07-23 13:52:21 -07006637/**
6638 * Sets focus to the window identified by the token. This must be called
6639 * after updating any input window handles.
6640 *
6641 * Params:
6642 * request.token - input channel token used to identify the window that should gain focus.
6643 * request.focusedToken - the token that the caller expects currently to be focused. If the
6644 * specified token does not match the currently focused window, this request will be dropped.
6645 * If the specified focused token matches the currently focused window, the call will succeed.
6646 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6647 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6648 * when requesting the focus change. This determines which request gets
6649 * precedence if there is a focus change request from another source such as pointer down.
6650 */
Vishnu Nair958da932020-08-21 17:12:37 -07006651void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6652 { // acquire lock
6653 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006654 std::optional<FocusResolver::FocusChanges> changes =
6655 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6656 if (changes) {
6657 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006658 }
6659 } // release lock
6660 // Wake up poll loop since it may need to make new input dispatching choices.
6661 mLooper->wake();
6662}
6663
Vishnu Nairc519ff72021-01-21 08:23:08 -08006664void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6665 if (changes.oldFocus) {
6666 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006667 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006668 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006669 "focus left window");
6670 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006671 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006672 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006673 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006674 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006675 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006676 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006677 }
6678
Prabir Pradhan99987712020-11-10 18:43:05 -08006679 // If a window has pointer capture, then it must have focus. We need to ensure that this
6680 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6681 // If the window loses focus before it loses pointer capture, then the window can be in a state
6682 // where it has pointer capture but not focus, violating the contract. Therefore we must
6683 // dispatch the pointer capture event before the focus event. Since focus events are added to
6684 // the front of the queue (above), we add the pointer capture event to the front of the queue
6685 // after the focus events are added. This ensures the pointer capture event ends up at the
6686 // front.
6687 disablePointerCaptureForcedLocked();
6688
Vishnu Nairc519ff72021-01-21 08:23:08 -08006689 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006690 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006691 }
6692}
Vishnu Nair958da932020-08-21 17:12:37 -07006693
Prabir Pradhan99987712020-11-10 18:43:05 -08006694void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006695 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006696 return;
6697 }
6698
6699 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6700
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006701 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006702 setPointerCaptureLocked(false);
6703 }
6704
6705 if (!mWindowTokenWithPointerCapture) {
6706 // No need to send capture changes because no window has capture.
6707 return;
6708 }
6709
6710 if (mPendingEvent != nullptr) {
6711 // Move the pending event to the front of the queue. This will give the chance
6712 // for the pending event to be dropped if it is a captured event.
6713 mInboundQueue.push_front(mPendingEvent);
6714 mPendingEvent = nullptr;
6715 }
6716
6717 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006718 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006719 mInboundQueue.push_front(std::move(entry));
6720}
6721
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006722void InputDispatcher::setPointerCaptureLocked(bool enable) {
6723 mCurrentPointerCaptureRequest.enable = enable;
6724 mCurrentPointerCaptureRequest.seq++;
6725 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006726 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006727 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006728 };
6729 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006730}
6731
Vishnu Nair599f1412021-06-21 10:39:58 -07006732void InputDispatcher::displayRemoved(int32_t displayId) {
6733 { // acquire lock
6734 std::scoped_lock _l(mLock);
6735 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006736 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006737 setFocusedApplicationLocked(displayId, nullptr);
6738 // Call focus resolver to clean up stale requests. This must be called after input windows
6739 // have been removed for the removed display.
6740 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006741 // Reset pointer capture eligibility, regardless of previous state.
6742 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006743 // Remove the associated touch mode state.
6744 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006745 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006746 } // release lock
6747
6748 // Wake up poll loop since it may need to make new input dispatching choices.
6749 mLooper->wake();
6750}
6751
Patrick Williamsd828f302023-04-28 17:52:08 -05006752void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006753 // The listener sends the windows as a flattened array. Separate the windows by display for
6754 // more convenient parsing.
6755 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006756 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006757 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006758 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006759 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006760
6761 { // acquire lock
6762 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006763
6764 // Ensure that we have an entry created for all existing displays so that if a displayId has
6765 // no windows, we can tell that the windows were removed from the display.
6766 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6767 handlesPerDisplay[displayId];
6768 }
6769
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006770 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006771 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006772 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6773 }
6774
6775 for (const auto& [displayId, handles] : handlesPerDisplay) {
6776 setInputWindowsLocked(handles, displayId);
6777 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006778
6779 if (update.vsyncId < mWindowInfosVsyncId) {
6780 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6781 ", current update vsync id: %" PRId64,
6782 mWindowInfosVsyncId, update.vsyncId);
6783 }
6784 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006785 }
6786 // Wake up poll loop since it may need to make new input dispatching choices.
6787 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006788}
6789
Vishnu Nair062a8672021-09-03 16:07:44 -07006790bool InputDispatcher::shouldDropInput(
6791 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006792 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6793 (windowHandle->getInfo()->inputConfig.test(
6794 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006795 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006796 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6797 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006798 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006799 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006800 windowHandle->getInfo()->displayId);
6801 return true;
6802 }
6803 return false;
6804}
6805
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006806void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006807 const gui::WindowInfosUpdate& update) {
6808 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006809}
6810
Arthur Hungdfd528e2021-12-08 13:23:04 +00006811void InputDispatcher::cancelCurrentTouch() {
6812 {
6813 std::scoped_lock _l(mLock);
6814 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006815 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006816 "cancel current touch");
6817 synthesizeCancelationEventsForAllConnectionsLocked(options);
6818
6819 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006820 }
6821 // Wake up poll loop since there might be work to do.
6822 mLooper->wake();
6823}
6824
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006825void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6826 std::scoped_lock _l(mLock);
6827 mMonitorDispatchingTimeout = timeout;
6828}
6829
Arthur Hungc539dbb2022-12-08 07:45:36 +00006830void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6831 const sp<WindowInfoHandle>& oldWindowHandle,
6832 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006833 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006834 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006835 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6836 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006837 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6838 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6839 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6840 newWindowHandle->getInfo()->inputConfig.test(
6841 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6842 const sp<WindowInfoHandle> oldWallpaper =
6843 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6844 const sp<WindowInfoHandle> newWallpaper =
6845 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6846 if (oldWallpaper == newWallpaper) {
6847 return;
6848 }
6849
6850 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006851 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006852 addPointerWindowTargetLocked(oldWallpaper,
6853 oldTouchedWindow.targetFlags |
6854 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6855 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId),
6856 targets);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006857 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006858 }
6859
6860 if (newWallpaper != nullptr) {
6861 state.addOrUpdateWindow(newWallpaper,
6862 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6863 InputTarget::Flags::WINDOW_IS_OBSCURED |
6864 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006865 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006866 }
6867}
6868
6869void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6870 ftl::Flags<InputTarget::Flags> newTargetFlags,
6871 const sp<WindowInfoHandle> fromWindowHandle,
6872 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006873 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006874 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006875 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6876 fromWindowHandle->getInfo()->inputConfig.test(
6877 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6878 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6879 toWindowHandle->getInfo()->inputConfig.test(
6880 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6881
6882 const sp<WindowInfoHandle> oldWallpaper =
6883 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6884 const sp<WindowInfoHandle> newWallpaper =
6885 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6886 if (oldWallpaper == newWallpaper) {
6887 return;
6888 }
6889
6890 if (oldWallpaper != nullptr) {
6891 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6892 "transferring touch focus to another window");
6893 state.removeWindowByToken(oldWallpaper->getToken());
6894 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6895 }
6896
6897 if (newWallpaper != nullptr) {
6898 nsecs_t downTimeInTarget = now();
6899 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6900 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6901 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6902 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006903 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6904 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006905 std::shared_ptr<Connection> wallpaperConnection =
6906 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006907 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006908 std::shared_ptr<Connection> toConnection =
6909 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006910 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6911 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6912 wallpaperFlags);
6913 }
6914 }
6915}
6916
6917sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6918 const sp<WindowInfoHandle>& windowHandle) const {
6919 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6920 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6921 bool foundWindow = false;
6922 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6923 if (!foundWindow && otherHandle != windowHandle) {
6924 continue;
6925 }
6926 if (windowHandle == otherHandle) {
6927 foundWindow = true;
6928 continue;
6929 }
6930
6931 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6932 return otherHandle;
6933 }
6934 }
6935 return nullptr;
6936}
6937
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006938void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6939 std::scoped_lock _l(mLock);
6940
6941 mConfig.keyRepeatTimeout = timeout;
6942 mConfig.keyRepeatDelay = delay;
6943}
6944
Garfield Tane84e6f92019-08-29 17:28:41 -07006945} // namespace android::inputdispatcher