blob: 639187a7dfd953cacbb745a90926e9c5229df777 [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
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// 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 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700122inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000123 if (binder == nullptr) {
124 return "<null>";
125 }
126 return StringPrintf("%p", binder.get());
127}
128
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000129static std::string uidString(const gui::Uid& uid) {
130 return uid.toString();
131}
132
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700133Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 case AKEY_EVENT_ACTION_DOWN:
136 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700137 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700139 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 }
141}
142
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700143Result<void> validateKeyEvent(int32_t action) {
144 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145}
146
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700147Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800148 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700150 case AMOTION_EVENT_ACTION_UP: {
151 if (pointerCount != 1) {
152 return Error() << "invalid pointer count " << pointerCount;
153 }
154 return {};
155 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
160 if (pointerCount < 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 case AMOTION_EVENT_ACTION_POINTER_DOWN:
170 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800171 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700172 if (index < 0) {
173 return Error() << "invalid index " << index << " for "
174 << MotionEvent::actionToString(action);
175 }
176 if (index >= pointerCount) {
177 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
178 }
179 if (pointerCount <= 1) {
180 return Error() << "invalid pointer count " << pointerCount << " for "
181 << MotionEvent::actionToString(action);
182 }
183 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 }
185 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700186 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
187 if (actionButton == 0) {
188 return Error() << "action button should be nonzero for "
189 << MotionEvent::actionToString(action);
190 }
191 return {};
192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700194 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 }
196}
197
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000198int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500199 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
200}
201
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700202Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
203 const PointerProperties* pointerProperties) {
204 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
205 if (!actionCheck.ok()) {
206 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 }
208 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700209 return Error() << "Motion event has invalid pointer count " << pointerCount
210 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800212 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 for (size_t i = 0; i < pointerCount; i++) {
214 int32_t id = pointerProperties[i].id;
215 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700216 return Error() << "Motion event has invalid pointer id " << id
217 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800219 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700220 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800222 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700224 return {};
225}
226
227Result<void> validateInputEvent(const InputEvent& event) {
228 switch (event.getType()) {
229 case InputEventType::KEY: {
230 const KeyEvent& key = static_cast<const KeyEvent&>(event);
231 const int32_t action = key.getAction();
232 return validateKeyEvent(action);
233 }
234 case InputEventType::MOTION: {
235 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
236 const int32_t action = motion.getAction();
237 const size_t pointerCount = motion.getPointerCount();
238 const PointerProperties* pointerProperties = motion.getPointerProperties();
239 const int32_t actionButton = motion.getActionButton();
240 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
241 }
242 default: {
243 return {};
244 }
245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246}
247
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800248std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
249 std::bitset<MAX_POINTER_ID + 1> pointerIds;
250 for (const PointerProperties& pointer : pointers) {
251 pointerIds.set(pointer.id);
252 }
253 return pointerIds;
254}
255
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000256std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 }
260
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000261 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 bool first = true;
263 Region::const_iterator cur = region.begin();
264 Region::const_iterator const tail = region.end();
265 while (cur != tail) {
266 if (first) {
267 first = false;
268 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800269 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800271 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272 cur++;
273 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000274 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275}
276
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000277std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
278 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500279 constexpr size_t maxEntries = 50; // max events to print
280 constexpr size_t skipBegin = maxEntries / 2;
281 const size_t skipEnd = queue.size() - maxEntries / 2;
282 // skip from maxEntries / 2 ... size() - maxEntries/2
283 // only print from 0 .. skipBegin and then from skipEnd .. size()
284
285 std::string dump;
286 for (size_t i = 0; i < queue.size(); i++) {
287 const DispatchEntry& entry = *queue[i];
288 if (i >= skipBegin && i < skipEnd) {
289 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
290 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
291 continue;
292 }
293 dump.append(INDENT4);
294 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000295 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
296 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500297 ns2ms(currentTime - entry.eventEntry->eventTime));
298 if (entry.deliveryTime != 0) {
299 // This entry was delivered, so add information on how long we've been waiting
300 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
301 }
302 dump.append("\n");
303 }
304 return dump;
305}
306
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700307/**
308 * Find the entry in std::unordered_map by key, and return it.
309 * If the entry is not found, return a default constructed entry.
310 *
311 * Useful when the entries are vectors, since an empty vector will be returned
312 * if the entry is not found.
313 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
314 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000316V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700317 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700318 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800319}
320
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000321bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700322 if (first == second) {
323 return true;
324 }
325
326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329
330 return first->getToken() == second->getToken();
331}
332
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000333bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000334 if (first == nullptr || second == nullptr) {
335 return false;
336 }
337 return first->applicationInfo.token != nullptr &&
338 first->applicationInfo.token == second->applicationInfo.token;
339}
340
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800341template <typename T>
342size_t firstMarkedBit(T set) {
343 // TODO: replace with std::countr_zero from <bit> when that's available
344 LOG_ALWAYS_FATAL_IF(set.none());
345 size_t i = 0;
346 while (!set.test(i)) {
347 i++;
348 }
349 return i;
350}
351
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800352std::unique_ptr<DispatchEntry> createDispatchEntry(
Prabir Pradhan24047542023-11-02 17:14:59 +0000353 const InputTarget& inputTarget, std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800354 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 if (inputTarget.useDefaultPointerTransform()) {
356 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700358 inputTarget.displayTransform,
359 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360 }
361
362 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700365 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700366 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 // Use the first pointer information to normalize all other pointers. This could be any pointer
369 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // uses the transform for the normalized pointer.
371 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800372 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700373 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374
375 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700376 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000377 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
378 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 // First, apply the current pointer's transform to update the coordinates into
383 // window space.
384 pointerCoords[pointerIndex].transform(currTransform);
385 // Next, apply the inverse transform of the normalized coordinates so the
386 // current coordinates are transformed into the normalized coordinate space.
387 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388 }
389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700390 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000391 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
392 motionEntry.eventTime, motionEntry.deviceId,
393 motionEntry.source, motionEntry.displayId,
394 motionEntry.policyFlags, motionEntry.action,
395 motionEntry.actionButton, motionEntry.flags,
396 motionEntry.metaState, motionEntry.buttonState,
397 motionEntry.classification, motionEntry.edgeFlags,
398 motionEntry.xPrecision, motionEntry.yPrecision,
399 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
400 motionEntry.downTime, motionEntry.pointerProperties,
401 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000402
403 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700404 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700405 firstPointerTransform, inputTarget.displayTransform,
406 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000407 return dispatchEntry;
408}
409
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000410status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
411 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700412 std::unique_ptr<InputChannel> uniqueServerChannel;
413 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
414
415 serverChannel = std::move(uniqueServerChannel);
416 return result;
417}
418
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500419template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000420bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500421 if (lhs == nullptr && rhs == nullptr) {
422 return true;
423 }
424 if (lhs == nullptr || rhs == nullptr) {
425 return false;
426 }
427 return *lhs == *rhs;
428}
429
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000430KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000431 KeyEvent event;
432 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
433 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
434 entry.repeatCount, entry.downTime, entry.eventTime);
435 return event;
436}
437
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000438bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000439 // Do not keep track of gesture monitors. They receive every event and would disproportionately
440 // affect the statistics.
441 if (connection.monitor) {
442 return false;
443 }
444 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
445 if (!connection.responsive) {
446 return false;
447 }
448 return true;
449}
450
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000451bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000452 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
453 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
455 return false;
456 }
457 // Only track latency for events that originated from hardware
458 if (eventEntry.isSynthesized()) {
459 return false;
460 }
461 const EventEntry::Type& inputEventEntryType = eventEntry.type;
462 if (inputEventEntryType == EventEntry::Type::KEY) {
463 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
464 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
465 return false;
466 }
467 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
468 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
469 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
470 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
471 return false;
472 }
473 } else {
474 // Not a key or a motion
475 return false;
476 }
477 if (!shouldReportMetricsForConnection(connection)) {
478 return false;
479 }
480 return true;
481}
482
Prabir Pradhancef936d2021-07-21 16:17:52 +0000483/**
484 * Connection is responsive if it has no events in the waitQueue that are older than the
485 * current time.
486 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000487bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000488 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000489 for (const auto& dispatchEntry : connection.waitQueue) {
490 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000491 return false;
492 }
493 }
494 return true;
495}
496
Antonio Kantekf16f2832021-09-28 04:39:20 +0000497// Returns true if the event type passed as argument represents a user activity.
498bool isUserActivityEvent(const EventEntry& eventEntry) {
499 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000500 case EventEntry::Type::CONFIGURATION_CHANGED:
501 case EventEntry::Type::DEVICE_RESET:
502 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000503 case EventEntry::Type::FOCUS:
504 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000505 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000506 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508 case EventEntry::Type::KEY:
509 case EventEntry::Type::MOTION:
510 return true;
511 }
512}
513
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800514// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000515bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000516 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800517 const auto inputConfig = windowInfo.inputConfig;
518 if (windowInfo.displayId != displayId ||
519 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800520 return false;
521 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700522 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800523 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524 return false;
525 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526
527 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
528 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
529 // the window. Points on the right and bottom edges should not be inside the window, so we need
530 // to be careful about performing a hit test when the display is rotated, since the "right" and
531 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
532 // logical display in which WM determined the bounds. Perform the hit test in the logical
533 // display space to ensure these edges are considered correctly in all orientations.
534 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
535 const auto p = displayTransform.transform(x, y);
536 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800537 return false;
538 }
539 return true;
540}
541
Prabir Pradhand65552b2021-10-07 11:23:50 -0700542bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
543 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000544 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700545}
546
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800547// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000548// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
549// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
550// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800551// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000552bool canReceiveForegroundTouches(const WindowInfo& info) {
553 // A non-touchable window can still receive touch events (e.g. in the case of
554 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
555 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
556}
557
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000558bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700559 if (windowHandle == nullptr) {
560 return false;
561 }
562 const WindowInfo* windowInfo = windowHandle->getInfo();
563 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
564 return true;
565 }
566 return false;
567}
568
Prabir Pradhan5735a322022-04-11 17:23:34 +0000569// Checks targeted injection using the window's owner's uid.
570// Returns an empty string if an entry can be sent to the given window, or an error message if the
571// entry is a targeted injection whose uid target doesn't match the window owner.
572std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
573 const EventEntry& entry) {
574 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
575 // The event was not injected, or the injected event does not target a window.
576 return {};
577 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000578 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000580 return StringPrintf("No valid window target for injection into uid %s.",
581 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000582 }
583 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000584 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
585 "owned by uid %s.",
586 uid.toString().c_str(), window->getName().c_str(),
587 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 }
589 return {};
590}
591
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000592std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700593 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
594 // Always dispatch mouse events to cursor position.
595 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000596 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700597 }
598
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700599 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000600 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
601 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602}
603
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700604std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
605 if (eventEntry.type == EventEntry::Type::KEY) {
606 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
607 return keyEntry.downTime;
608 } else if (eventEntry.type == EventEntry::Type::MOTION) {
609 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
610 return motionEntry.downTime;
611 }
612 return std::nullopt;
613}
614
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000615/**
616 * Compare the old touch state to the new touch state, and generate the corresponding touched
617 * windows (== input targets).
618 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
619 * If the pointer just entered the new window, produce HOVER_ENTER.
620 * For pointers remaining in the window, produce HOVER_MOVE.
621 */
622std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
623 const TouchState& newTouchState,
624 const MotionEntry& entry) {
625 std::vector<TouchedWindow> out;
626 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700627
628 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
629 // ACTION_SCROLL events should not affect the hovering pointer dispatch
630 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000631 }
632
633 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800634 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000635
636 std::set<sp<WindowInfoHandle>> oldWindows;
637 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800638 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000639 }
640
641 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800642 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000643
644 // If the pointer is no longer in the new window set, send HOVER_EXIT.
645 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
646 if (newWindows.find(oldWindow) == newWindows.end()) {
647 TouchedWindow touchedWindow;
648 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000649 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000650 out.push_back(touchedWindow);
651 }
652 }
653
654 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
655 TouchedWindow touchedWindow;
656 touchedWindow.windowHandle = newWindow;
657 if (oldWindows.find(newWindow) == oldWindows.end()) {
658 // Any windows that have this pointer now, and didn't have it before, should get
659 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000660 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000661 } else {
662 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700663 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700664 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000665 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
666 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700667 // The Accessibility injected touch exploration event stream
668 // has known inconsistencies, so log ERROR instead of
669 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700670 severity = android::base::LogSeverity::ERROR;
671 }
672 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000674 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000675 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800676 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
678 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
679 }
680 out.push_back(touchedWindow);
681 }
682 return out;
683}
684
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800685template <typename T>
686std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
687 left.insert(left.end(), right.begin(), right.end());
688 return left;
689}
690
Harry Cuttsb166c002023-05-09 13:06:05 +0000691// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
692// both.
693void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
694 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
695 if (!window.windowHandle->getInfo()->inputConfig.test(
696 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
697 // In addition to TouchState, erase this window from the input targets! We don't have a
698 // good way to do this today except by adding a nested loop.
699 // TODO(b/282025641): simplify this code once InputTargets are being identified
700 // separately from TouchedWindows.
701 std::erase_if(targets, [&](const InputTarget& target) {
702 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
703 });
704 return true;
705 }
706 return false;
707 });
708}
709
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700710/**
711 * In general, touch should be always split between windows. Some exceptions:
712 * 1. Don't split touch if all of the below is true:
713 * (a) we have an active pointer down *and*
714 * (b) a new pointer is going down that's from the same device *and*
715 * (c) the window that's receiving the current pointer does not support split touch.
716 * 2. Don't split mouse events
717 */
718bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
719 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
720 // We should never split mouse events
721 return false;
722 }
723 for (const TouchedWindow& touchedWindow : touchState.windows) {
724 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
725 // Spy windows should not affect whether or not touch is split.
726 continue;
727 }
728 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
729 continue;
730 }
731 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
732 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
733 // Wallpaper window should not affect whether or not touch is split
734 continue;
735 }
736
737 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
738 return false;
739 }
740 }
741 return true;
742}
743
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700744/**
745 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
746 */
747bool isStylusActiveInDisplay(
748 int32_t displayId,
749 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
750 const auto it = touchStatesByDisplay.find(displayId);
751 if (it == touchStatesByDisplay.end()) {
752 return false;
753 }
754 const TouchState& state = it->second;
755 return state.hasActiveStylus();
756}
757
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800758Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
759 struct HashFunction {
760 size_t operator()(const WindowInfo& info) const { return info.id; }
761 };
762
763 std::unordered_set<WindowInfo, HashFunction> windowSet;
764 for (const WindowInfo& info : update.windowInfos) {
765 const auto [_, inserted] = windowSet.insert(info);
766 if (!inserted) {
767 return Error() << "Duplicate entry for " << info;
768 }
769 }
770 return {};
771}
772
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000773} // namespace
774
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775// --- InputDispatcher ---
776
Prabir Pradhana41d2442023-04-20 21:30:40 +0000777InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Garfield Tan00f511d2019-06-12 16:55:40 -0700778 : mPolicy(policy),
779 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800781 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700782 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800783 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700784 mDispatchEnabled(false),
785 mDispatchFrozen(false),
786 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100787 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000788 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800789 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000790 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000791 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700792 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800793 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700795 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700796#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700797 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700798#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700799 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800}
801
802InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000803 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804
Prabir Pradhancef936d2021-07-21 16:17:52 +0000805 resetKeyRepeatLocked();
806 releasePendingEventLocked();
807 drainInboundQueueLocked();
808 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000810 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700811 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000812 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 }
814}
815
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700816status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700817 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700818 return ALREADY_EXISTS;
819 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700820 mThread = std::make_unique<InputThread>(
821 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
822 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700823}
824
825status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700826 if (mThread && mThread->isCallingThread()) {
827 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700828 return INVALID_OPERATION;
829 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700830 mThread.reset();
831 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700832}
833
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700835 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800837 std::scoped_lock _l(mLock);
838 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
840 // Run a dispatch loop if there are no pending commands.
841 // The dispatch loop might enqueue commands to run afterwards.
842 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800843 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 }
845
846 // Run all pending commands if there are any.
847 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000848 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700849 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800851
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700852 // If we are still waiting for ack on some events,
853 // we might have to wake up earlier to check if an app is anr'ing.
854 const nsecs_t nextAnrCheck = processAnrsLocked();
855 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
856
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800857 // We are about to enter an infinitely long sleep, because we have no commands or
858 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700859 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800860 mDispatcherEnteredIdle.notify_all();
861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 } // release lock
863
864 // Wait for callback or timeout or wake. (make sure we round up, not down)
865 nsecs_t currentTime = now();
866 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
867 mLooper->pollOnce(timeoutMillis);
868}
869
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700870/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500871 * Raise ANR if there is no focused window.
872 * Before the ANR is raised, do a final state check:
873 * 1. The currently focused application must be the same one we are waiting for.
874 * 2. Ensure we still don't have a focused window.
875 */
876void InputDispatcher::processNoFocusedWindowAnrLocked() {
877 // Check if the application that we are waiting for is still focused.
878 std::shared_ptr<InputApplicationHandle> focusedApplication =
879 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
880 if (focusedApplication == nullptr ||
881 focusedApplication->getApplicationToken() !=
882 mAwaitedFocusedApplication->getApplicationToken()) {
883 // Unexpected because we should have reset the ANR timer when focused application changed
884 ALOGE("Waited for a focused window, but focused application has already changed to %s",
885 focusedApplication->getName().c_str());
886 return; // The focused application has changed.
887 }
888
chaviw98318de2021-05-19 16:45:23 -0500889 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500890 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
891 if (focusedWindowHandle != nullptr) {
892 return; // We now have a focused window. No need for ANR.
893 }
894 onAnrLocked(mAwaitedFocusedApplication);
895}
896
897/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 * Check if any of the connections' wait queues have events that are too old.
899 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
900 * Return the time at which we should wake up next.
901 */
902nsecs_t InputDispatcher::processAnrsLocked() {
903 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700904 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700905 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
906 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
907 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500908 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700909 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500910 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700911 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500913 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
915 }
916 }
917
918 // Check if any connection ANRs are due
919 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
920 if (currentTime < nextAnrCheck) { // most likely scenario
921 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
922 }
923
924 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700925 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700926 if (connection == nullptr) {
927 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
928 return nextAnrCheck;
929 }
930 connection->responsive = false;
931 // Stop waking up for this unresponsive connection
932 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000933 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700934 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935}
936
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800937std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700938 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800939 if (connection->monitor) {
940 return mMonitorDispatchingTimeout;
941 }
942 const sp<WindowInfoHandle> window =
943 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500945 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500947 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948}
949
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800950void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 nsecs_t currentTime = now();
952
Jeff Browndc5992e2014-04-11 01:27:26 -0700953 // Reset the key repeat timer whenever normal dispatch is suspended while the
954 // device is in a non-interactive state. This is to ensure that we abort a key
955 // repeat if the device is just coming out of sleep.
956 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 resetKeyRepeatLocked();
958 }
959
960 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
961 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100962 if (DEBUG_FOCUS) {
963 ALOGD("Dispatch frozen. Waiting some more.");
964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 return;
966 }
967
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 // Ready to start a new event.
969 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700970 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700971 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 // Synthesize a key repeat if appropriate.
973 if (mKeyRepeatState.lastKeyEntry) {
974 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
975 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
976 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800977 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
979 }
980
981 // Nothing to do if there is no pending event.
982 if (!mPendingEvent) {
983 return;
984 }
985 } else {
986 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700987 mPendingEvent = mInboundQueue.front();
988 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 traceInboundQueueLengthLocked();
990 }
991
992 // Poke user activity for this event.
993 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700994 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
997
998 // Now we have an event to dispatch.
999 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001000 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001002 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001006 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 }
1008
1009 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012
1013 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001014 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001015 const ConfigurationChangedEntry& typedEntry =
1016 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001018 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 break;
1020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001022 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001023 const DeviceResetEntry& typedEntry =
1024 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001026 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 break;
1028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001030 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001031 std::shared_ptr<const FocusEntry> typedEntry =
1032 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 dispatchFocusLocked(currentTime, typedEntry);
1034 done = true;
1035 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1036 break;
1037 }
1038
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001039 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001040 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001041 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1042 done = true;
1043 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1044 break;
1045 }
1046
Prabir Pradhan99987712020-11-10 18:43:05 -08001047 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1048 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001049 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001050 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1051 done = true;
1052 break;
1053 }
1054
arthurhungb89ccb02020-12-30 16:19:01 +08001055 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001056 std::shared_ptr<const DragEntry> typedEntry =
1057 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001058 dispatchDragLocked(currentTime, typedEntry);
1059 done = true;
1060 break;
1061 }
1062
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001063 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001064 std::shared_ptr<const KeyEntry> keyEntry =
1065 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001066 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001067 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1070 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001072 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 break;
1074 }
1075
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001076 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001077 std::shared_ptr<const MotionEntry> motionEntry =
1078 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001079 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001080 // The event is stale. However, only drop stale events if there isn't an ongoing
1081 // gesture. That would allow us to complete the processing of the current stroke.
1082 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1083 if (touchStateIt != mTouchStatesByDisplay.end()) {
1084 const TouchState& touchState = touchStateIt->second;
1085 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1086 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1087 dropReason = DropReason::STALE;
1088 }
1089 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001092 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1093 // Only drop events that are focus-dispatched.
1094 dropReason = DropReason::BLOCKED;
1095 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001097 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 }
Chris Yef59a2f42020-10-16 12:55:26 -07001100
1101 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001102 std::shared_ptr<const SensorEntry> sensorEntry =
1103 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001104
Chris Yef59a2f42020-10-16 12:55:26 -07001105 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1106 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1107 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1108 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1109 dropReason = DropReason::STALE;
1110 }
1111 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1112 done = true;
1113 break;
1114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
1116
1117 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001119 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
Michael Wright3a981722015-06-10 15:26:13 +01001121 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122
1123 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001124 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126}
1127
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001128bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001129 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001130}
1131
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001132/**
1133 * Return true if the events preceding this incoming motion event should be dropped
1134 * Return false otherwise (the default behaviour)
1135 */
1136bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001137 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001138 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001139
1140 // Optimize case where the current application is unresponsive and the user
1141 // decides to touch a window in a different application.
1142 // If the application takes too long to catch up then we drop all events preceding
1143 // the touch into the other window.
1144 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001145 const int32_t displayId = motionEntry.displayId;
1146 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001147 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001148
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001149 sp<WindowInfoHandle> touchedWindowHandle =
1150 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001151 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001152 touchedWindowHandle->getApplicationToken() !=
1153 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001155 ALOGI("Pruning input queue because user touched a different application while waiting "
1156 "for %s",
1157 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001158 return true;
1159 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001160
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001161 // Alternatively, maybe there's a spy window that could handle this event.
1162 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1163 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1164 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001165 const std::shared_ptr<Connection> connection =
1166 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001167 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001168 // This spy window could take more input. Drop all events preceding this
1169 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001170 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001171 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001172 mAwaitedFocusedApplication->getName().c_str());
1173 return true;
1174 }
1175 }
1176 }
1177
1178 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1179 // yet been processed by some connections, the dispatcher will wait for these motion
1180 // events to be processed before dispatching the key event. This is because these motion events
1181 // may cause a new window to be launched, which the user might expect to receive focus.
1182 // To prevent waiting forever for such events, just send the key to the currently focused window
1183 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1184 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1185 "just send the pending key event to the focused window.");
1186 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001187 }
1188 return false;
1189}
1190
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001194 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 traceInboundQueueLengthLocked();
1196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001198 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001199 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1200 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001203
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001204 // If a new up event comes in, and the pending event with same key code has been asked
1205 // to try again later because of the policy. We have to reset the intercept key wake up
1206 // time for it may have been handled in the policy and could be dropped.
1207 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1208 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001209 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001210 if (pendingKey.keyCode == keyEntry.keyCode &&
1211 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001212 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1213 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001214 pendingKey.interceptKeyWakeupTime = 0;
1215 needWake = true;
1216 }
1217 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001218 break;
1219 }
1220
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001221 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001222 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1223 "Unexpected untrusted event.");
Prabir Pradhan24047542023-11-02 17:14:59 +00001224 if (shouldPruneInboundQueueLocked(static_cast<const MotionEntry&>(entry))) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001226 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001230 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001231 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1232 break;
1233 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001234 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001235 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001236 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001237 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001238 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1239 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001240 // nothing to do
1241 break;
1242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244
1245 return needWake;
1246}
1247
Prabir Pradhan24047542023-11-02 17:14:59 +00001248void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001249 // Do not store sensor event in recent queue to avoid flooding the queue.
1250 if (entry->type != EventEntry::Type::SENSOR) {
1251 mRecentQueue.push_back(entry);
1252 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001253 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001254 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256}
1257
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001258sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1259 bool isStylus,
1260 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001262 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001263 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001264 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001265 continue;
1266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001268 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001269 if (!info.isSpy() &&
1270 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001271 return windowHandle;
1272 }
1273 }
1274 return nullptr;
1275}
1276
1277std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001278 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001279 if (touchedWindow == nullptr) {
1280 return {};
1281 }
1282 // Traverse windows from front to back until we encounter the touched window.
1283 std::vector<InputTarget> outsideTargets;
1284 const auto& windowHandles = getWindowHandlesLocked(displayId);
1285 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1286 if (windowHandle == touchedWindow) {
1287 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1288 // below the touched window will not get ACTION_OUTSIDE event.
1289 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001290 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001291
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001292 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001293 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001294 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1295 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001296 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1297 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001298 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001301 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302}
1303
Prabir Pradhand65552b2021-10-07 11:23:50 -07001304std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001305 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001306 // Traverse windows from front to back and gather the touched spy windows.
1307 std::vector<sp<WindowInfoHandle>> spyWindows;
1308 const auto& windowHandles = getWindowHandlesLocked(displayId);
1309 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1310 const WindowInfo& info = *windowHandle->getInfo();
1311
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001312 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001313 continue;
1314 }
1315 if (!info.isSpy()) {
1316 // The first touched non-spy window was found, so return the spy windows touched so far.
1317 return spyWindows;
1318 }
1319 spyWindows.push_back(windowHandle);
1320 }
1321 return spyWindows;
1322}
1323
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001324void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 const char* reason;
1326 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001327 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001328 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001329 ALOGD("Dropped event because policy consumed it.");
1330 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331 reason = "inbound event was dropped because the policy consumed it";
1332 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001333 case DropReason::DISABLED:
1334 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335 ALOGI("Dropped event because input dispatch is disabled.");
1336 }
1337 reason = "inbound event was dropped because input dispatch is disabled";
1338 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001339 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001340 LOG(INFO) << "Dropping because the current application is not responding and the user "
1341 "has started interacting with a different application: "
1342 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001343 reason = "inbound event was dropped because the current application is not responding "
1344 "and the user has started interacting with a different application";
1345 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001346 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 ALOGI("Dropped event because it is stale.");
1348 reason = "inbound event was dropped because it is stale";
1349 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001350 case DropReason::NO_POINTER_CAPTURE:
1351 ALOGI("Dropped event because there is no window with Pointer Capture.");
1352 reason = "inbound event was dropped because there is no window with Pointer Capture";
1353 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001354 case DropReason::NOT_DROPPED: {
1355 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001360 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001361 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001362 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001363 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1364 options.displayId = keyEntry.displayId;
1365 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001367 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001369 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001370 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1371 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001372 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001373 options.displayId = motionEntry.displayId;
1374 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001375 synthesizeCancelationEventsForAllConnectionsLocked(options);
1376 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001377 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1378 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001379 options.displayId = motionEntry.displayId;
1380 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 synthesizeCancelationEventsForAllConnectionsLocked(options);
1382 }
1383 break;
1384 }
Chris Yef59a2f42020-10-16 12:55:26 -07001385 case EventEntry::Type::SENSOR: {
1386 break;
1387 }
arthurhungb89ccb02020-12-30 16:19:01 +08001388 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1389 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 break;
1391 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001392 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001393 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001394 case EventEntry::Type::CONFIGURATION_CHANGED:
1395 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001396 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001397 break;
1398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 }
1400}
1401
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001403 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404}
1405
Prabir Pradhancef936d2021-07-21 16:17:52 +00001406bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001407 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 return false;
1409 }
1410
1411 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001412 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001413 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001414 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1415 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001416 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 return true;
1418}
1419
Prabir Pradhancef936d2021-07-21 16:17:52 +00001420void InputDispatcher::postCommandLocked(Command&& command) {
1421 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422}
1423
1424void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001425 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001426 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001427 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 releaseInboundEventLocked(entry);
1429 }
1430 traceInboundQueueLengthLocked();
1431}
1432
1433void InputDispatcher::releasePendingEventLocked() {
1434 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001436 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
1438}
1439
Prabir Pradhan24047542023-11-02 17:14:59 +00001440void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001441 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001442 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001443 if (DEBUG_DISPATCH_CYCLE) {
1444 ALOGD("Injected inbound event was dropped.");
1445 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
1448 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001449 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 }
1451 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452}
1453
1454void InputDispatcher::resetKeyRepeatLocked() {
1455 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001456 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 }
1458}
1459
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001460std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001461 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
Michael Wright2e732952014-09-24 13:26:59 -07001463 uint32_t policyFlags = entry->policyFlags &
1464 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001466 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001467 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1468 currentTime, entry->deviceId, entry->source,
1469 entry->displayId, policyFlags, entry->action, entry->flags,
1470 entry->keyCode, entry->scanCode, entry->metaState,
1471 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473 newEntry->syntheticRepeat = true;
1474 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001476 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477}
1478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001479bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001480 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001481 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1482 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484
1485 // Reset key repeating in case a keyboard device was added or removed or something.
1486 resetKeyRepeatLocked();
1487
1488 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001489 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1490 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001491 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001492 };
1493 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 return true;
1495}
1496
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001497bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1498 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001499 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1500 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1501 entry.deviceId);
1502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503
liushenxiang42232912021-05-21 20:24:09 +08001504 // Reset key repeating in case a keyboard device was disabled or enabled.
1505 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1506 resetKeyRepeatLocked();
1507 }
1508
Michael Wrightfb04fd52022-11-24 22:31:11 +00001509 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001512
1513 // Remove all active pointers from this device
1514 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1515 touchState.removeAllPointersForDevice(entry.deviceId);
1516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 return true;
1518}
1519
Vishnu Nairad321cd2020-08-20 16:40:21 -07001520void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001521 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001522 if (mPendingEvent != nullptr) {
1523 // Move the pending event to the front of the queue. This will give the chance
1524 // for the pending event to get dispatched to the newly focused window
1525 mInboundQueue.push_front(mPendingEvent);
1526 mPendingEvent = nullptr;
1527 }
1528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001529 std::unique_ptr<FocusEntry> focusEntry =
1530 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1531 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001532
1533 // This event should go to the front of the queue, but behind all other focus events
1534 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001535 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1536 [](const std::shared_ptr<const EventEntry>& event) {
1537 return event->type == EventEntry::Type::FOCUS;
1538 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001539
1540 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001541 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001542}
1543
Prabir Pradhan24047542023-11-02 17:14:59 +00001544void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1545 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001546 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001547 if (channel == nullptr) {
1548 return; // Window has gone away
1549 }
1550 InputTarget target;
1551 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001552 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001553 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1554 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001555 std::string reason = std::string("reason=").append(entry->reason);
1556 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001557 dispatchEventLocked(currentTime, entry, {target});
1558}
1559
Prabir Pradhan99987712020-11-10 18:43:05 -08001560void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001561 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001562 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001563 dropReason = DropReason::NOT_DROPPED;
1564
Prabir Pradhan99987712020-11-10 18:43:05 -08001565 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001566 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001567
1568 if (entry->pointerCaptureRequest.enable) {
1569 // Enable Pointer Capture.
1570 if (haveWindowWithPointerCapture &&
1571 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001572 // This can happen if pointer capture is disabled and re-enabled before we notify the
1573 // app of the state change, so there is no need to notify the app.
1574 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1575 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001576 }
1577 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001578 // This can happen if a window requests capture and immediately releases capture.
1579 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001580 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001581 return;
1582 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001583 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1584 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1585 return;
1586 }
1587
Vishnu Nairc519ff72021-01-21 08:23:08 -08001588 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001589 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1590 mWindowTokenWithPointerCapture = token;
1591 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001592 // Disable Pointer Capture.
1593 // We do not check if the sequence number matches for requests to disable Pointer Capture
1594 // for two reasons:
1595 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1596 // to disable capture with the same sequence number: one generated by
1597 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1598 // Capture being disabled in InputReader.
1599 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1600 // actual Pointer Capture state that affects events being generated by input devices is
1601 // in InputReader.
1602 if (!haveWindowWithPointerCapture) {
1603 // Pointer capture was already forcefully disabled because of focus change.
1604 dropReason = DropReason::NOT_DROPPED;
1605 return;
1606 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001607 token = mWindowTokenWithPointerCapture;
1608 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001609 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001610 setPointerCaptureLocked(false);
1611 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001612 }
1613
1614 auto channel = getInputChannelLocked(token);
1615 if (channel == nullptr) {
1616 // Window has gone away, clean up Pointer Capture state.
1617 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001618 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001619 setPointerCaptureLocked(false);
1620 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001621 return;
1622 }
1623 InputTarget target;
1624 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001625 entry->dispatchInProgress = true;
1626 dispatchEventLocked(currentTime, entry, {target});
1627
1628 dropReason = DropReason::NOT_DROPPED;
1629}
1630
Prabir Pradhan24047542023-11-02 17:14:59 +00001631void InputDispatcher::dispatchTouchModeChangeLocked(
1632 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001633 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001634 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001635 if (windowHandles.empty()) {
1636 return;
1637 }
1638 const std::vector<InputTarget> inputTargets =
1639 getInputTargetsFromWindowHandlesLocked(windowHandles);
1640 if (inputTargets.empty()) {
1641 return;
1642 }
1643 entry->dispatchInProgress = true;
1644 dispatchEventLocked(currentTime, entry, inputTargets);
1645}
1646
1647std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1648 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1649 std::vector<InputTarget> inputTargets;
1650 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001651 const sp<IBinder>& token = handle->getToken();
1652 if (token == nullptr) {
1653 continue;
1654 }
1655 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1656 if (channel == nullptr) {
1657 continue; // Window has gone away
1658 }
1659 InputTarget target;
1660 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001661 inputTargets.push_back(target);
1662 }
1663 return inputTargets;
1664}
1665
Prabir Pradhan24047542023-11-02 17:14:59 +00001666bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001667 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001669 if (!entry->dispatchInProgress) {
1670 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1671 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1672 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1673 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001674 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 // We have seen two identical key downs in a row which indicates that the device
1676 // driver is automatically generating key repeats itself. We take note of the
1677 // repeat here, but we disable our own next key repeat timer since it is clear that
1678 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001679 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1680 // Make sure we don't get key down from a different device. If a different
1681 // device Id has same key pressed down, the new device Id will replace the
1682 // current one to hold the key repeat with repeat count reset.
1683 // In the future when got a KEY_UP on the device id, drop it and do not
1684 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1686 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001687 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 } else {
1689 // Not a repeat. Save key down state in case we do see a repeat later.
1690 resetKeyRepeatLocked();
1691 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1692 }
1693 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001694 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1695 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001696 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001697 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001698 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1699 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001700 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 resetKeyRepeatLocked();
1702 }
1703
1704 if (entry->repeatCount == 1) {
1705 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1706 } else {
1707 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1708 }
1709
1710 entry->dispatchInProgress = true;
1711
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001712 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
1714
1715 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001716 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001718 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 return false; // wait until next wakeup
1720 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001721 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 entry->interceptKeyWakeupTime = 0;
1723 }
1724
1725 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001726 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001728 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001729 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001730
1731 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1732 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1733 };
1734 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001735 // Poke user activity for keys not passed to user
1736 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 return false; // wait for the command to run
1738 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001739 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001741 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001742 if (*dropReason == DropReason::NOT_DROPPED) {
1743 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745 }
1746
1747 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001748 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001749 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1751 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001752 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001753 // Poke user activity for undispatched keys
1754 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 return true;
1756 }
1757
1758 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001759 InputEventInjectionResult injectionResult;
1760 sp<WindowInfoHandle> focusedWindow =
1761 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1762 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001763 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 return false;
1765 }
1766
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001767 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001768 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 return true;
1770 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001771 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1772
1773 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001774 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1775 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001777 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001778 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779
1780 // Dispatch the key.
1781 dispatchEventLocked(currentTime, entry, inputTargets);
1782 return true;
1783}
1784
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001785void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001786 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1787 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1788 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1789 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1790 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1791 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1792 entry.metaState, entry.repeatCount, entry.downTime);
1793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794}
1795
Prabir Pradhancef936d2021-07-21 16:17:52 +00001796void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001797 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001798 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001799 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1800 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1801 "source=0x%x, sensorType=%s",
1802 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001803 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001804 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001805 auto command = [this, entry]() REQUIRES(mLock) {
1806 scoped_unlock unlock(mLock);
1807
1808 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001809 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001810 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001811 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1812 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001813 };
1814 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001815}
1816
1817bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001818 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1819 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001820 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001821 }
Chris Yef59a2f42020-10-16 12:55:26 -07001822 { // acquire lock
1823 std::scoped_lock _l(mLock);
1824
1825 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001826 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001827 if (entry->type == EventEntry::Type::SENSOR) {
1828 it = mInboundQueue.erase(it);
1829 releaseInboundEventLocked(entry);
1830 }
1831 }
1832 }
1833 return true;
1834}
1835
Prabir Pradhan24047542023-11-02 17:14:59 +00001836bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1837 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001838 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001839 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001841 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 entry->dispatchInProgress = true;
1843
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001844 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 }
1846
1847 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001848 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001849 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001850 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1851 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 return true;
1853 }
1854
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001855 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
1857 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001858 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001860 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 if (isPointerEvent) {
1862 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001863
1864 if (mDragState &&
1865 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1866 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1867 pilferPointersLocked(mDragState->dragWindow->getToken());
1868 }
1869
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001870 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001871 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001872 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1873 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 } else {
1875 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001876 sp<WindowInfoHandle> focusedWindow =
1877 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1878 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1879 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001880 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1881 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1882 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001885 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 return false;
1887 }
1888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001889 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001890 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001891 return true;
1892 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001894 CancelationOptions::Mode mode(
1895 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1896 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001897 CancelationOptions options(mode, "input event injection failed");
1898 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 return true;
1900 }
1901
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001902 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001903 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 dispatchEventLocked(currentTime, entry, inputTargets);
1907 return true;
1908}
1909
chaviw98318de2021-05-19 16:45:23 -05001910void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001911 bool isExiting, const int32_t rawX,
1912 const int32_t rawY) {
1913 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001914 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001915 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1916 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001917
1918 enqueueInboundEventLocked(std::move(dragEntry));
1919}
1920
Prabir Pradhan24047542023-11-02 17:14:59 +00001921void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
1922 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08001923 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1924 if (channel == nullptr) {
1925 return; // Window has gone away
1926 }
1927 InputTarget target;
1928 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08001929 entry->dispatchInProgress = true;
1930 dispatchEventLocked(currentTime, entry, {target});
1931}
1932
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001933void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001934 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001935 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001936 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001937 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 "metaState=0x%x, buttonState=0x%x,"
1939 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001940 prefix, entry.eventTime, entry.deviceId,
1941 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1942 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1943 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1944 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07001946 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001947 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001948 "x=%f, y=%f, pressure=%f, size=%f, "
1949 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1950 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001951 i, entry.pointerProperties[i].id,
1952 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001953 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1954 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1955 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1956 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1957 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1958 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1959 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1960 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1961 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964}
1965
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001966void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001967 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001968 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001970 if (DEBUG_DISPATCH_CYCLE) {
1971 ALOGD("dispatchEventToCurrentInputTargets");
1972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001974 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001975
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1977
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001978 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001980 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001981 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001982 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001983 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001984 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07001986 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
1987 LOG(INFO) << "Dropping event delivery to target with channel "
1988 << inputTarget.inputChannel->getName()
1989 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992 }
1993}
1994
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001995void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1997 // If the policy decides to close the app, we will get a channel removal event via
1998 // unregisterInputChannel, and will clean up the connection that way. We are already not
1999 // sending new pointers to the connection when it blocked, but focused events will continue to
2000 // pile up.
2001 ALOGW("Canceling events for %s because it is unresponsive",
2002 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002003 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002004 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 "application not responding");
2006 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
2008}
2009
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002010void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002011 if (DEBUG_FOCUS) {
2012 ALOGD("Resetting ANR timeouts.");
2013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
2015 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002016 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002017 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018}
2019
Tiger Huang721e26f2018-07-24 22:26:19 +08002020/**
2021 * Get the display id that the given event should go to. If this event specifies a valid display id,
2022 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2023 * Focused display is the display that the user most recently interacted with.
2024 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002025int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002026 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002027 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002028 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002029 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2030 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002031 break;
2032 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002033 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2035 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 break;
2037 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002038 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002039 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002040 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002041 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002042 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002043 case EventEntry::Type::SENSOR:
2044 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002045 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046 return ADISPLAY_ID_NONE;
2047 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002048 }
2049 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2050}
2051
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2053 const char* focusedWindowName) {
2054 if (mAnrTracker.empty()) {
2055 // already processed all events that we waited for
2056 mKeyIsWaitingForEventsTimeout = std::nullopt;
2057 return false;
2058 }
2059
2060 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2061 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002062 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002063 mKeyIsWaitingForEventsTimeout = currentTime +
2064 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2065 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002066 return true;
2067 }
2068
2069 // We still have pending events, and already started the timer
2070 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2071 return true; // Still waiting
2072 }
2073
2074 // Waited too long, and some connection still hasn't processed all motions
2075 // Just send the key to the focused window
2076 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2077 focusedWindowName);
2078 mKeyIsWaitingForEventsTimeout = std::nullopt;
2079 return false;
2080}
2081
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002082sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002083 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002084 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002085 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Tiger Huang721e26f2018-07-24 22:26:19 +08002087 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002088 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002089 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002090 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2091
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 // If there is no currently focused window and no focused application
2093 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002094 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2095 ALOGI("Dropping %s event because there is no focused window or focused application in "
2096 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002097 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002098 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 }
2100
Vishnu Nair062a8672021-09-03 16:07:44 -07002101 // Drop key events if requested by input feature
2102 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002103 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002104 }
2105
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002106 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2107 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2108 // start interacting with another application via touch (app switch). This code can be removed
2109 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2110 // an app is expected to have a focused window.
2111 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2112 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2113 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002114 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2115 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2116 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002118 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 ALOGW("Waiting because no window has focus but %s may eventually add a "
2120 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002121 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002122 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002123 outInjectionResult = InputEventInjectionResult::PENDING;
2124 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2126 // Already raised ANR. Drop the event
2127 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002128 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002129 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002130 } else {
2131 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002132 outInjectionResult = InputEventInjectionResult::PENDING;
2133 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002134 }
2135 }
2136
2137 // we have a valid, non-null focused window
2138 resetNoFocusedWindowTimeoutLocked();
2139
Prabir Pradhan5735a322022-04-11 17:23:34 +00002140 // Verify targeted injection.
2141 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2142 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002143 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2144 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 }
2146
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002147 if (focusedWindowHandle->getInfo()->inputConfig.test(
2148 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002149 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 outInjectionResult = InputEventInjectionResult::PENDING;
2151 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002152 }
2153
2154 // If the event is a key event, then we must wait for all previous events to
2155 // complete before delivering it because previous events may have the
2156 // side-effect of transferring focus to a different window and we want to
2157 // ensure that the following keys are sent to the new window.
2158 //
2159 // Suppose the user touches a button in a window then immediately presses "A".
2160 // If the button causes a pop-up window to appear then we want to ensure that
2161 // the "A" key is delivered to the new pop-up window. This is because users
2162 // often anticipate pending UI changes when typing on a keyboard.
2163 // To obtain this behavior, we must serialize key events with respect to all
2164 // prior input events.
2165 if (entry.type == EventEntry::Type::KEY) {
2166 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002167 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002168 outInjectionResult = InputEventInjectionResult::PENDING;
2169 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 }
2172
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002173 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2174 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175}
2176
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177/**
2178 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2179 * that are currently unresponsive.
2180 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002181std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2182 const std::vector<Monitor>& monitors) const {
2183 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002184 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002185 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002186 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002187 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 if (connection == nullptr) {
2189 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002190 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002191 return false;
2192 }
2193 if (!connection->responsive) {
2194 ALOGW("Unresponsive monitor %s will not get the new gesture",
2195 connection->inputChannel->getName().c_str());
2196 return false;
2197 }
2198 return true;
2199 });
2200 return responsiveMonitors;
2201}
2202
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002203std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002204 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002205 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002206 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002208 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 // For security reasons, we defer updating the touch state until we are sure that
2210 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002211 const int32_t displayId = entry.displayId;
2212 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002213 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214
2215 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002216 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 // Copy current touch state into tempTouchState.
2219 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2220 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002221 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002222 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002223 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2224 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002225 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002226 }
2227
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002228 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002229
2230 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2231 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2232 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002233 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2234 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002235 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002236 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2237 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002238 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2239 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2240 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002241 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002242
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002243 if (newGesture) {
2244 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002245 }
2246
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002247 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2248 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2249 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 }
2251
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002252 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002253 if (wasDown) {
2254 // Started hovering, but the device is already down: reject the hover event
2255 LOG(ERROR) << "Got hover event " << entry.getDescription()
2256 << " but the device is already down " << oldState->dump();
2257 outInjectionResult = InputEventInjectionResult::FAILED;
2258 return {};
2259 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002260 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2261 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002262 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002263 }
2264
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2266 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002267 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002268 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002269 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002270 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2271 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002272 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002273 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002274 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002275
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002276 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002277 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002280 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002281 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 }
2285
Prabir Pradhan5735a322022-04-11 17:23:34 +00002286 // Verify targeted injection.
2287 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2288 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002289 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002290 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002291 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002292 }
2293
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002294 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002295 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002296 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2297 // New window supports splitting, but we should never split mouse events.
2298 isSplit = !isFromMouse;
2299 } else if (isSplit) {
2300 // New window does not support splitting but we have already split events.
2301 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002302 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2303 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002304 newTouchedWindowHandle = nullptr;
2305 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002306 } else {
2307 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002308 // be delivered to a new window which supports split touch. Pointers from a mouse device
2309 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002310 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002311 }
2312
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002313 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002314 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002315 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002316 // Process the foreground window first so that it is the first to receive the event.
2317 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002318 }
2319
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002320 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002321 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2322 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002323 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002324 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002325 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002326 }
2327
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002328 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002329 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002330 continue;
2331 }
2332
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002333 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002334 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002335 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002336 }
2337
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002338 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002339 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002340
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002341 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2342 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002343 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002344 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002345
2346 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002347 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002348 }
2349 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002350 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002352 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002354
2355 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002356
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002357 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002358 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2359 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002360 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002361 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002362 isDownOrPointerDown
2363 ? std::make_optional(entry.eventTime)
2364 : std::nullopt);
2365 // If this is the pointer going down and the touched window has a wallpaper
2366 // then also add the touched wallpaper windows so they are locked in for the
2367 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2368 // SCROLL because the wallpaper engine only supports touch events. We would need to
2369 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2370 // handle these events.
2371 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002372 windowHandle->getInfo()->inputConfig.test(
2373 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2374 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2375 if (wallpaper != nullptr) {
2376 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2377 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002378 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002379 if (isSplit) {
2380 wallpaperFlags |= InputTarget::Flags::SPLIT;
2381 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002382 tempTouchState.addOrUpdateWindow(wallpaper,
2383 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002384 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002385 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002386 }
2387 }
2388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002390
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002391 // If a window is already pilfering some pointers, give it this new pointer as well and
2392 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2393 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002394 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002395 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002396 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002397 // This window is already pilfering some pointers, and this new pointer is also
2398 // going to it. Therefore, take over this pointer and don't give it to anyone
2399 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002400 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002401 }
2402 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002403
2404 // Restrict all pilfered pointers to the pilfering windows.
2405 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 } else {
2407 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2408
2409 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002410 if (!tempTouchState.isDown(entry.deviceId) &&
2411 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002412 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2413 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2414 << " is not down or we previously dropped the pointer down event in "
2415 << "display " << displayId << ": " << entry.getDescription();
2416 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002417 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002418 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
2420
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002421 // If the pointer is not currently hovering, then ignore the event.
2422 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2423 const int32_t pointerId = entry.pointerProperties[0].id;
2424 if (oldState == nullptr ||
2425 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2426 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2427 "display "
2428 << displayId << ": " << entry.getDescription();
2429 outInjectionResult = InputEventInjectionResult::FAILED;
2430 return {};
2431 }
2432 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2433 }
2434
arthurhung6d4bed92021-03-17 11:59:33 +08002435 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002436
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002438 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002439 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002440 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002441 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002442 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002443 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002444 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002445 sp<WindowInfoHandle> newTouchedWindowHandle =
2446 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002447
Prabir Pradhan5735a322022-04-11 17:23:34 +00002448 // Verify targeted injection.
2449 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2450 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002451 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002452 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002453 }
2454
Vishnu Nair062a8672021-09-03 16:07:44 -07002455 // Drop touch events if requested by input feature
2456 if (newTouchedWindowHandle != nullptr &&
2457 shouldDropInput(entry, newTouchedWindowHandle)) {
2458 newTouchedWindowHandle = nullptr;
2459 }
2460
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002461 if (newTouchedWindowHandle != nullptr &&
2462 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002463 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002464 oldTouchedWindowHandle->getName().c_str(),
2465 newTouchedWindowHandle->getName().c_str(), displayId);
2466
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002468 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002469 const PointerProperties& pointer = entry.pointerProperties[0];
2470 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002471
2472 const TouchedWindow& touchedWindow =
2473 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002474 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002475 InputTarget::DispatchMode::SLIPPERY_EXIT,
2476 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002477 touchedWindow.getDownTimeInTarget(entry.deviceId),
2478 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479
2480 // Make a slippery entrance into the new window.
2481 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002482 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002485 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002486 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002487 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002490 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
2492 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002493 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002494 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002495 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 }
2497
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002498 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2499 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002500 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002501 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002502
2503 // Check if the wallpaper window should deliver the corresponding event.
2504 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002505 tempTouchState, entry.deviceId, pointer, targets);
2506 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002507 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 }
2509 }
Arthur Hung96483742022-11-15 03:30:48 +00002510
2511 // Update the pointerIds for non-splittable when it received pointer down.
2512 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2513 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002514 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002515 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2516 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002517 // Ignore drag window for it should just track one pointer.
2518 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2519 continue;
2520 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002521 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002522 }
2523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 }
2525
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002526 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002527 {
2528 std::vector<TouchedWindow> hoveringWindows =
2529 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2530 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002531 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002532 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2533 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002534 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002535 if (!target) {
2536 continue;
2537 }
2538 // Hardcode to single hovering pointer for now.
2539 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2540 pointerIds.set(entry.pointerProperties[0].id);
2541 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2542 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545
Prabir Pradhan5735a322022-04-11 17:23:34 +00002546 // Ensure that all touched windows are valid for injection.
2547 if (entry.injectionState != nullptr) {
2548 std::string errs;
2549 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002550 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2551 if (err) errs += "\n - " + *err;
2552 }
2553 if (!errs.empty()) {
2554 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002555 "%s:%s",
2556 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002557 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002558 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002559 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002560 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002561
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002562 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2563 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002565 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002566 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002567 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002568 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002569 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002570 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002571 sp<WindowInfoHandle> targetWindow =
2572 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2573 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2574 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 }
2577 }
2578 }
2579 }
2580
Harry Cuttsb166c002023-05-09 13:06:05 +00002581 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2582 // only want the system UI to handle these gestures.
2583 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2584 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2585 if (isTouchpadNavGesture) {
2586 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2587 }
2588
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002589 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002590 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002591 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002592 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002593 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002594 continue;
2595 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002596 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002597 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002598 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002599 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002600
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002601 // During targeted injection, only allow owned targets to receive events
2602 std::erase_if(targets, [&](const InputTarget& target) {
2603 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2604 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2605 if (err) {
2606 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2607 << ": " << (*err);
2608 return true;
2609 }
2610 return false;
2611 });
2612
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002613 if (targets.empty()) {
2614 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2615 outInjectionResult = InputEventInjectionResult::FAILED;
2616 return {};
2617 }
2618
2619 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2620 // window that is actually receiving the entire gesture.
2621 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002622 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002623 })) {
2624 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2625 << entry.getDescription();
2626 outInjectionResult = InputEventInjectionResult::FAILED;
2627 return {};
2628 }
2629
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002630 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631
Prabir Pradhan502a7252023-12-01 16:11:24 +00002632 // Now that we have generated all of the input targets for this event, reset the dispatch
2633 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002634 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002635 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002636 }
2637
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002638 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002639 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002640 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002641 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002642 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002643 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002644 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002645 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2646 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002647 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2648 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2649 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 }
2651
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002652 // Save changes unless the action was scroll in which case the temporary touch
2653 // state was only valid for this one action.
2654 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002655 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002656 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002657 mTouchStatesByDisplay[displayId] = tempTouchState;
2658 } else {
2659 mTouchStatesByDisplay.erase(displayId);
2660 }
2661 }
2662
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002663 if (tempTouchState.windows.empty()) {
2664 mTouchStatesByDisplay.erase(displayId);
2665 }
2666
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002667 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668}
2669
arthurhung6d4bed92021-03-17 11:59:33 +08002670void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002671 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2672 // have an explicit reason to support it.
2673 constexpr bool isStylus = false;
2674
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002675 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002676 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002677 if (dropWindow) {
2678 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002679 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002680 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002681 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002682 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002683 }
2684 mDragState.reset();
2685}
2686
2687void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002688 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002689 return;
2690 }
2691
arthurhung6d4bed92021-03-17 11:59:33 +08002692 if (!mDragState->isStartDrag) {
2693 mDragState->isStartDrag = true;
2694 mDragState->isStylusButtonDownAtStart =
2695 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2696 }
2697
Arthur Hung54745652022-04-20 07:17:41 +00002698 // Find the pointer index by id.
2699 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002700 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002701 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2702 if (pointerProperties.id == mDragState->pointerId) {
2703 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002704 }
Arthur Hung54745652022-04-20 07:17:41 +00002705 }
arthurhung6d4bed92021-03-17 11:59:33 +08002706
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002707 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002708 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002709 }
2710
2711 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2712 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2713 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2714
2715 switch (maskedAction) {
2716 case AMOTION_EVENT_ACTION_MOVE: {
2717 // Handle the special case : stylus button no longer pressed.
2718 bool isStylusButtonDown =
2719 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2720 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2721 finishDragAndDrop(entry.displayId, x, y);
2722 return;
2723 }
2724
2725 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2726 // until we have an explicit reason to support it.
2727 constexpr bool isStylus = false;
2728
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002729 sp<WindowInfoHandle> hoverWindowHandle =
2730 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2731 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002732 // enqueue drag exit if needed.
2733 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2734 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2735 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002736 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002737 y);
2738 }
2739 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2740 }
2741 // enqueue drag location if needed.
2742 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002743 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002744 }
2745 break;
2746 }
2747
2748 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002749 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002750 break;
2751 }
2752 // The drag pointer is up.
2753 [[fallthrough]];
2754 case AMOTION_EVENT_ACTION_UP:
2755 finishDragAndDrop(entry.displayId, x, y);
2756 break;
2757 case AMOTION_EVENT_ACTION_CANCEL: {
2758 ALOGD("Receiving cancel when drag and drop.");
2759 sendDropWindowCommandLocked(nullptr, 0, 0);
2760 mDragState.reset();
2761 break;
2762 }
arthurhungb89ccb02020-12-30 16:19:01 +08002763 }
2764}
2765
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002766std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2767 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002768 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002769 std::optional<nsecs_t> firstDownTimeInTarget) const {
2770 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2771 if (inputChannel == nullptr) {
2772 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2773 return {};
2774 }
2775 InputTarget inputTarget;
2776 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002777 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002778 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002779 inputTarget.flags = targetFlags;
2780 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2781 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2782 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2783 if (displayInfoIt != mDisplayInfos.end()) {
2784 inputTarget.displayTransform = displayInfoIt->second.transform;
2785 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002786 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002787 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2788 }
2789 return inputTarget;
2790}
2791
chaviw98318de2021-05-19 16:45:23 -05002792void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002793 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002794 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002795 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002796 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002797 std::vector<InputTarget>::iterator it =
2798 std::find_if(inputTargets.begin(), inputTargets.end(),
2799 [&windowHandle](const InputTarget& inputTarget) {
2800 return inputTarget.inputChannel->getConnectionToken() ==
2801 windowHandle->getToken();
2802 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002803
chaviw98318de2021-05-19 16:45:23 -05002804 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002805
2806 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002807 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002808 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2809 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002810 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002811 return;
2812 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002813 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002814 it = inputTargets.end() - 1;
2815 }
2816
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002817 if (it->flags != targetFlags) {
2818 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2819 }
2820 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2821 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2822 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2823 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002824}
2825
2826void InputDispatcher::addPointerWindowTargetLocked(
2827 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002828 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2829 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2830 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002831 if (pointerIds.none()) {
2832 for (const auto& target : inputTargets) {
2833 LOG(INFO) << "Target: " << target;
2834 }
2835 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2836 return;
2837 }
2838 std::vector<InputTarget>::iterator it =
2839 std::find_if(inputTargets.begin(), inputTargets.end(),
2840 [&windowHandle](const InputTarget& inputTarget) {
2841 return inputTarget.inputChannel->getConnectionToken() ==
2842 windowHandle->getToken();
2843 });
2844
2845 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2846 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2847 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2848 // input targets for hovering pointers and for touching pointers.
2849 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2850 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002851 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002852 // Force the code below to create a new input target
2853 it = inputTargets.end();
2854 }
2855
2856 const WindowInfo* windowInfo = windowHandle->getInfo();
2857
2858 if (it == inputTargets.end()) {
2859 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002860 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2861 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002862 if (!target) {
2863 return;
2864 }
2865 inputTargets.push_back(*target);
2866 it = inputTargets.end() - 1;
2867 }
2868
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002869 if (it->dispatchMode != dispatchMode) {
2870 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2871 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2872 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002873 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002874 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2875 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002876 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002877 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002878 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002879 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2880 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002881
chaviw1ff3d1e2020-07-01 15:53:47 -07002882 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883}
2884
Michael Wright3dd60e22019-03-27 22:06:44 +00002885void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002886 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002887 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2888 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002889
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002890 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2891 InputTarget target;
2892 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002893 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2894 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002895 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2896 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002897 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002898 target.setDefaultPointerTransform(target.displayTransform);
2899 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
2901}
2902
Robert Carrc9bf1d32020-04-13 17:21:08 -07002903/**
2904 * Indicate whether one window handle should be considered as obscuring
2905 * another window handle. We only check a few preconditions. Actually
2906 * checking the bounds is left to the caller.
2907 */
chaviw98318de2021-05-19 16:45:23 -05002908static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2909 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002910 // Compare by token so cloned layers aren't counted
2911 if (haveSameToken(windowHandle, otherHandle)) {
2912 return false;
2913 }
2914 auto info = windowHandle->getInfo();
2915 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002916 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002917 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002918 } else if (otherInfo->alpha == 0 &&
2919 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002920 // Those act as if they were invisible, so we don't need to flag them.
2921 // We do want to potentially flag touchable windows even if they have 0
2922 // opacity, since they can consume touches and alter the effects of the
2923 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002924 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002925 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2926 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002927 } else if (info->ownerUid == otherInfo->ownerUid) {
2928 // If ownerUid is the same we don't generate occlusion events as there
2929 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002930 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002931 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932 return false;
2933 } else if (otherInfo->displayId != info->displayId) {
2934 return false;
2935 }
2936 return true;
2937}
2938
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002939/**
2940 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2941 * untrusted, one should check:
2942 *
2943 * 1. If result.hasBlockingOcclusion is true.
2944 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2945 * BLOCK_UNTRUSTED.
2946 *
2947 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2948 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2949 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2950 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2951 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2952 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2953 *
2954 * If neither of those is true, then it means the touch can be allowed.
2955 */
2956InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002957 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2958 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002959 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002960 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002961 TouchOcclusionInfo info;
2962 info.hasBlockingOcclusion = false;
2963 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002964 info.obscuringUid = gui::Uid::INVALID;
2965 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002966 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002967 if (windowHandle == otherHandle) {
2968 break; // All future windows are below us. Exit early.
2969 }
chaviw98318de2021-05-19 16:45:23 -05002970 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002971 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2972 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002973 if (DEBUG_TOUCH_OCCLUSION) {
2974 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00002975 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002976 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002977 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2978 // we perform the checks below to see if the touch can be propagated or not based on the
2979 // window's touch occlusion mode
2980 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2981 info.hasBlockingOcclusion = true;
2982 info.obscuringUid = otherInfo->ownerUid;
2983 info.obscuringPackage = otherInfo->packageName;
2984 break;
2985 }
2986 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002987 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002988 float opacity =
2989 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2990 // Given windows A and B:
2991 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2992 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2993 opacityByUid[uid] = opacity;
2994 if (opacity > info.obscuringOpacity) {
2995 info.obscuringOpacity = opacity;
2996 info.obscuringUid = uid;
2997 info.obscuringPackage = otherInfo->packageName;
2998 }
2999 }
3000 }
3001 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003002 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003003 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003004 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003005 return info;
3006}
3007
chaviw98318de2021-05-19 16:45:23 -05003008std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003009 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003010 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003011 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3012 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3013 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003014 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003015 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003016 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3017 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003018 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3019 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3020 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003021 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003022}
3023
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003024bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3025 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003026 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3027 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003028 return false;
3029 }
3030 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003031 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003032 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003033 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003034 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3035 return false;
3036 }
3037 return true;
3038}
3039
chaviw98318de2021-05-19 16:45:23 -05003040bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003043 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3044 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003045 if (windowHandle == otherHandle) {
3046 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
chaviw98318de2021-05-19 16:45:23 -05003048 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003049 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003050 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 return true;
3052 }
3053 }
3054 return false;
3055}
3056
chaviw98318de2021-05-19 16:45:23 -05003057bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003058 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003059 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3060 const WindowInfo* windowInfo = windowHandle->getInfo();
3061 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003062 if (windowHandle == otherHandle) {
3063 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003064 }
chaviw98318de2021-05-19 16:45:23 -05003065 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003066 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003067 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003068 return true;
3069 }
3070 }
3071 return false;
3072}
3073
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003074std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003075 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003076 if (applicationHandle != nullptr) {
3077 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003078 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 } else {
3080 return applicationHandle->getName();
3081 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003082 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003083 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003085 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087}
3088
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003090 if (!isUserActivityEvent(eventEntry)) {
3091 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003092 return;
3093 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003094 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003095 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003096 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003097 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003098 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003099 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003100 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102 }
3103
3104 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003105 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003106 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003107 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3108 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 return;
3110 }
Josep del Riob3981622023-04-18 15:49:45 +00003111 if (windowDisablingUserActivityInfo != nullptr) {
3112 if (DEBUG_DISPATCH_CYCLE) {
3113 ALOGD("Not poking user activity: disabled by window '%s'.",
3114 windowDisablingUserActivityInfo->name.c_str());
3115 }
3116 return;
3117 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 eventType = USER_ACTIVITY_EVENT_TOUCH;
3120 }
3121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003123 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003124 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3125 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 return;
3127 }
Josep del Riob3981622023-04-18 15:49:45 +00003128 // If the key code is unknown, we don't consider it user activity
3129 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3130 return;
3131 }
3132 // Don't inhibit events that were intercepted or are not passed to
3133 // the apps, like system shortcuts
3134 if (windowDisablingUserActivityInfo != nullptr &&
3135 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3136 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3137 if (DEBUG_DISPATCH_CYCLE) {
3138 ALOGD("Not poking user activity: disabled by window '%s'.",
3139 windowDisablingUserActivityInfo->name.c_str());
3140 }
3141 return;
3142 }
3143
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 eventType = USER_ACTIVITY_EVENT_BUTTON;
3145 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003147 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003148 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003149 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003150 break;
3151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153
Prabir Pradhancef936d2021-07-21 16:17:52 +00003154 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3155 REQUIRES(mLock) {
3156 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003157 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003158 };
3159 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160}
3161
3162void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003163 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003164 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003165 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003166 ATRACE_NAME_IF(ATRACE_ENABLED(),
3167 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3168 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003169 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003170 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003171 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003172 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003173 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003174 inputTarget.getPointerInfoString().c_str());
3175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176
3177 // Skip this event if the connection status is not normal.
3178 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003179 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003180 if (DEBUG_DISPATCH_CYCLE) {
3181 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003182 connection->getInputChannelName().c_str(),
3183 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 return;
3186 }
3187
3188 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003189 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003190 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003192 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003194 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003195 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003196 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3197 logDispatchStateLocked();
3198 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3199 "target on connection "
3200 << connection->getInputChannelName() << " for "
3201 << originalMotionEntry.getDescription();
3202 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003203 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003204 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3205 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 if (!splitMotionEntry) {
3207 return; // split event was dropped
3208 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003209 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3210 std::string reason = std::string("reason=pointer cancel on split window");
3211 android_log_event_list(LOGTAG_INPUT_CANCEL)
3212 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3213 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003214 if (DEBUG_FOCUS) {
3215 ALOGD("channel '%s' ~ Split motion event.",
3216 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003217 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003218 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003219 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3220 std::move(splitMotionEntry),
3221 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 return;
3223 }
3224 }
3225
3226 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003227 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3228 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229}
3230
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003231void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3232 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3233 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003234 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003235 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3236 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003237 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003238
hongzuo liu95785e22022-09-06 02:51:35 +00003239 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003241 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242
3243 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003244 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 startDispatchCycleLocked(currentTime, connection);
3246 }
3247}
3248
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003249void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003250 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003251 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 // This is a new event.
3253 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003254 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003255 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003257 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3258 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003259 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003261 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003262 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003263 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3264 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003265 LOG(WARNING) << "channel " << connection->getInputChannelName()
3266 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 return; // skip the inconsistent event
3268 }
3269 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003272 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003273 std::shared_ptr<const MotionEntry> resolvedMotion =
3274 std::static_pointer_cast<const MotionEntry>(eventEntry);
3275 {
3276 // Determine the resolved motion entry.
3277 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3278 int32_t resolvedAction = motionEntry.action;
3279 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003281 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003282 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003283 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003284 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003285 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003286 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003287 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003288 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003289 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003290 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3291 }
3292 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3293 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3294 motionEntry.displayId)) {
3295 if (DEBUG_DISPATCH_CYCLE) {
3296 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3297 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3298 "enter event";
3299 }
3300 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3301 }
3302
3303 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3304 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3305 }
3306 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3307 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3308 }
3309 if (dispatchEntry->targetFlags.test(
3310 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3311 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3312 }
3313
3314 dispatchEntry->resolvedFlags = resolvedFlags;
3315 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003316 std::optional<std::vector<PointerProperties>> usingProperties;
3317 std::optional<std::vector<PointerCoords>> usingCoords;
3318 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3319 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3320 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3321 // the dispatcher, and therefore the coordinates of this event are currently
3322 // incorrect. These events should use the coordinates of the last dispatched
3323 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3324 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3325 std::optional<std::pair<std::vector<PointerProperties>,
3326 std::vector<PointerCoords>>>
3327 pointerInfo =
3328 connection->inputState.getPointersOfLastEvent(motionEntry,
3329 hovering);
3330 if (pointerInfo) {
3331 usingProperties = pointerInfo->first;
3332 usingCoords = pointerInfo->second;
3333 }
3334 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003335 // Generate a new MotionEntry with a new eventId using the resolved action and
3336 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003337 resolvedMotion = std::make_shared<
3338 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3339 motionEntry.eventTime, motionEntry.deviceId,
3340 motionEntry.source, motionEntry.displayId,
3341 motionEntry.policyFlags, resolvedAction,
3342 motionEntry.actionButton, resolvedFlags,
3343 motionEntry.metaState, motionEntry.buttonState,
3344 motionEntry.classification, motionEntry.edgeFlags,
3345 motionEntry.xPrecision, motionEntry.yPrecision,
3346 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3347 motionEntry.downTime,
3348 usingProperties.value_or(motionEntry.pointerProperties),
3349 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003350 if (ATRACE_ENABLED()) {
3351 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3352 ") to MotionEvent(id=0x%" PRIx32 ").",
3353 motionEntry.id, resolvedMotion->id);
3354 ATRACE_NAME(message.c_str());
3355 }
3356
3357 // Set the resolved motion entry in the DispatchEntry.
3358 dispatchEntry->eventEntry = resolvedMotion;
3359 eventEntry = resolvedMotion;
3360 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003363 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3364 // devices being active at the same time in the same window, so if a new device is
3365 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003366 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003367 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003368 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003369 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003370 << connection->getInputChannelName() << " with event "
3371 << cancelEvent->getDescription();
3372 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3373 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003374 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003375
3376 // Send these cancel events to the queue before sending the event from the new
3377 // device.
3378 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3379 }
3380
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003381 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003383 LOG(WARNING) << "channel " << connection->getInputChannelName()
3384 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 return; // skip the inconsistent event
3386 }
3387
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003388 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3389 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003390 // Skip reporting pointer down outside focus to the policy.
3391 break;
3392 }
3393
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003394 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003395 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396
3397 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003399 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003400 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003401 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3402 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003403 break;
3404 }
Chris Yef59a2f42020-10-16 12:55:26 -07003405 case EventEntry::Type::SENSOR: {
3406 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3407 break;
3408 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003409 case EventEntry::Type::CONFIGURATION_CHANGED:
3410 case EventEntry::Type::DEVICE_RESET: {
3411 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003412 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003413 break;
3414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
3416
3417 // Remember that we are waiting for this dispatch to complete.
3418 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003419 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 }
3421
3422 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003423 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003424 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003425}
3426
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003427/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003428 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003429 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003430 * The first role is to log input interaction with windows, which helps determine what the user was
3431 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3432 * that user started interacting with launcher window, as well as any other window that received
3433 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3434 * when the set of tokens that received the event changes. It is not logged again as long as the
3435 * user is interacting with the same windows.
3436 *
3437 * The second role is to track input device activity for metrics collection. For each input event,
3438 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3439 * input_interaction logs, the device interaction is reported even when the set of interaction
3440 * tokens do not change.
3441 *
3442 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3443 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003444 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003445void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3446 const std::vector<InputTarget>& targets) {
3447 int32_t deviceId;
3448 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003449 // Skip ACTION_UP events, and all events other than keys and motions
3450 if (entry.type == EventEntry::Type::KEY) {
3451 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3452 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3453 return;
3454 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003455 deviceId = keyEntry.deviceId;
3456 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003457 } else if (entry.type == EventEntry::Type::MOTION) {
3458 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3459 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003460 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3461 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003462 return;
3463 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003464 deviceId = motionEntry.deviceId;
3465 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003466 } else {
3467 return; // Not a key or a motion
3468 }
3469
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003470 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003471 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003472 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003473 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003474 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 continue; // Skip windows that receive ACTION_OUTSIDE
3476 }
3477
3478 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003479 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003480 if (connection == nullptr) {
3481 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003482 }
3483 newConnectionTokens.insert(std::move(token));
3484 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003485 if (target.windowHandle) {
3486 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3487 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003488 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003489
3490 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3491 REQUIRES(mLock) {
3492 scoped_unlock unlock(mLock);
3493 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3494 };
3495 postCommandLocked(std::move(command));
3496
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003497 if (newConnectionTokens == mInteractionConnectionTokens) {
3498 return; // no change
3499 }
3500 mInteractionConnectionTokens = newConnectionTokens;
3501
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003503 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003504 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003505 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003506 std::string message = "Interaction with: " + targetList;
3507 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003508 message += "<none>";
3509 }
3510 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3511}
3512
chaviwfd6d3512019-03-25 13:23:49 -07003513void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003514 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003515 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003516 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3517 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003518 return;
3519 }
3520
Vishnu Nairc519ff72021-01-21 08:23:08 -08003521 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003522 if (focusedToken == token) {
3523 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003524 return;
3525 }
3526
Prabir Pradhancef936d2021-07-21 16:17:52 +00003527 auto command = [this, token]() REQUIRES(mLock) {
3528 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003529 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003530 };
3531 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532}
3533
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003534status_t InputDispatcher::publishMotionEvent(Connection& connection,
3535 DispatchEntry& dispatchEntry) const {
3536 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3537 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3538
3539 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003540 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003541
3542 // Set the X and Y offset and X and Y scale depending on the input source.
3543 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003544 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003545 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3546 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003547 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003548 scaledCoords[i] = motionEntry.pointerCoords[i];
3549 // Don't apply window scale here since we don't want scale to affect raw
3550 // coordinates. The scale will be sent back to the client and applied
3551 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003552 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003553 }
3554 usingCoords = scaledCoords;
3555 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003556 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003557 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003558 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003559 scaledCoords[i].clear();
3560 }
3561 usingCoords = scaledCoords;
3562 }
3563
3564 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3565
3566 // Publish the motion event.
3567 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003568 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3569 motionEntry.source, motionEntry.displayId, std::move(hmac),
3570 motionEntry.action, motionEntry.actionButton,
3571 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3572 motionEntry.metaState, motionEntry.buttonState,
3573 motionEntry.classification, dispatchEntry.transform,
3574 motionEntry.xPrecision, motionEntry.yPrecision,
3575 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3576 dispatchEntry.rawTransform, motionEntry.downTime,
3577 motionEntry.eventTime, motionEntry.getPointerCount(),
3578 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003579}
3580
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003582 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003583 ATRACE_NAME_IF(ATRACE_ENABLED(),
3584 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3585 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003586 if (DEBUG_DISPATCH_CYCLE) {
3587 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003590 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003591 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003593 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003594 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595
3596 // Publish the event.
3597 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3599 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003600 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003601 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3602 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003603 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003604 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3605 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003608 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003609 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003610 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3611 keyEntry.deviceId, keyEntry.source,
3612 keyEntry.displayId, std::move(hmac),
3613 keyEntry.action, dispatchEntry->resolvedFlags,
3614 keyEntry.keyCode, keyEntry.scanCode,
3615 keyEntry.metaState, keyEntry.repeatCount,
3616 keyEntry.downTime, keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003617 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003620 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003621 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003622 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3623 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003624 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003625 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626 break;
3627 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003629 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003631 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003633 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003634 break;
3635 }
3636
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003637 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3638 const TouchModeEntry& touchModeEntry =
3639 static_cast<const TouchModeEntry&>(eventEntry);
3640 status = connection->inputPublisher
3641 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3642 touchModeEntry.inTouchMode);
3643
3644 break;
3645 }
3646
Prabir Pradhan99987712020-11-10 18:43:05 -08003647 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3648 const auto& captureEntry =
3649 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3650 status = connection->inputPublisher
3651 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003652 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 break;
3654 }
3655
arthurhungb89ccb02020-12-30 16:19:01 +08003656 case EventEntry::Type::DRAG: {
3657 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3658 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3659 dragEntry.id, dragEntry.x,
3660 dragEntry.y,
3661 dragEntry.isExiting);
3662 break;
3663 }
3664
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003665 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003666 case EventEntry::Type::DEVICE_RESET:
3667 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003668 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003669 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673
3674 // Check the result.
3675 if (status) {
3676 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003677 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003679 "This is unexpected because the wait queue is empty, so the pipe "
3680 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003681 "event to it, status=%s(%d)",
3682 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3683 status);
Harry Cutts33476232023-01-30 19:57:29 +00003684 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 } else {
3686 // Pipe is full and we are waiting for the app to finish process some events
3687 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003688 if (DEBUG_DISPATCH_CYCLE) {
3689 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3690 "waiting for the application to catch up",
3691 connection->getInputChannelName().c_str());
3692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
3694 } else {
3695 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003696 "status=%s(%d)",
3697 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3698 status);
Harry Cutts33476232023-01-30 19:57:29 +00003699 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701 return;
3702 }
3703
3704 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003705 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3706 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3707 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003708 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003709 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003710 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003711 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003712 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 }
3714}
3715
chaviw09c8d2d2020-08-24 15:48:26 -07003716std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3717 size_t size;
3718 switch (event.type) {
3719 case VerifiedInputEvent::Type::KEY: {
3720 size = sizeof(VerifiedKeyEvent);
3721 break;
3722 }
3723 case VerifiedInputEvent::Type::MOTION: {
3724 size = sizeof(VerifiedMotionEvent);
3725 break;
3726 }
3727 }
3728 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3729 return mHmacKeyManager.sign(start, size);
3730}
3731
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003732const std::array<uint8_t, 32> InputDispatcher::getSignature(
3733 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003734 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003735 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003736 // Only sign events up and down events as the purely move events
3737 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003739 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003740
3741 VerifiedMotionEvent verifiedEvent =
3742 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3743 verifiedEvent.actionMasked = actionMasked;
3744 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3745 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003746}
3747
3748const std::array<uint8_t, 32> InputDispatcher::getSignature(
3749 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3750 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3751 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003752 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003753}
3754
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003756 const std::shared_ptr<Connection>& connection,
3757 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003758 if (DEBUG_DISPATCH_CYCLE) {
3759 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3760 connection->getInputChannelName().c_str(), seq, toString(handled));
3761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003763 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 return;
3765 }
3766
3767 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003768 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3769 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3770 };
3771 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
3774void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003775 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003778 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3779 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003784 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
3788 // The connection appears to be unrecoverably broken.
3789 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003790 if (connection->status == Connection::Status::NORMAL) {
3791 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
3793 if (notify) {
3794 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003795 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3796 connection->getInputChannelName().c_str());
3797
3798 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003799 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003800 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 };
3802 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 }
3805}
3806
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003807void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003808 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003810 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812}
3813
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003814void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003816 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818}
3819
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003820int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3821 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003822 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823 if (connection == nullptr) {
3824 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3825 connectionToken.get(), events);
3826 return 0; // remove the callback
3827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003829 bool notify;
3830 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3831 if (!(events & ALOOPER_EVENT_INPUT)) {
3832 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3833 "events=0x%x",
3834 connection->getInputChannelName().c_str(), events);
3835 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003838 nsecs_t currentTime = now();
3839 bool gotOne = false;
3840 status_t status = OK;
3841 for (;;) {
3842 Result<InputPublisher::ConsumerResponse> result =
3843 connection->inputPublisher.receiveConsumerResponse();
3844 if (!result.ok()) {
3845 status = result.error().code();
3846 break;
3847 }
3848
3849 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3850 const InputPublisher::Finished& finish =
3851 std::get<InputPublisher::Finished>(*result);
3852 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3853 finish.consumeTime);
3854 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003855 if (shouldReportMetricsForConnection(*connection)) {
3856 const InputPublisher::Timeline& timeline =
3857 std::get<InputPublisher::Timeline>(*result);
3858 mLatencyTracker
3859 .trackGraphicsLatency(timeline.inputEventId,
3860 connection->inputChannel->getConnectionToken(),
3861 std::move(timeline.graphicsTimeline));
3862 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003863 }
3864 gotOne = true;
3865 }
3866 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003867 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003868 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 return 1;
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
3872
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003873 notify = status != DEAD_OBJECT || !connection->monitor;
3874 if (notify) {
3875 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3876 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3877 status);
3878 }
3879 } else {
3880 // Monitor channels are never explicitly unregistered.
3881 // We do it automatically when the remote endpoint is closed so don't warn about them.
3882 const bool stillHaveWindowHandle =
3883 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3884 notify = !connection->monitor && stillHaveWindowHandle;
3885 if (notify) {
3886 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3887 connection->getInputChannelName().c_str(), events);
3888 }
3889 }
3890
3891 // Remove the channel.
3892 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3893 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894}
3895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003898 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003899 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 }
3901}
3902
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003904 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003905 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003906 for (const Monitor& monitor : monitors) {
3907 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003908 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003909 }
3910}
3911
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003913 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003914 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003915 if (connection == nullptr) {
3916 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918
3919 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920}
3921
3922void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003923 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00003924 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 return;
3926 }
3927
3928 nsecs_t currentTime = now();
3929
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003930 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003931 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003933 if (cancelationEvents.empty()) {
3934 return;
3935 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00003936
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003937 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3938 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003939 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003940 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003941 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003942 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003943
Arthur Hungb3307ee2021-10-14 10:57:37 +00003944 std::string reason = std::string("reason=").append(options.reason);
3945 android_log_event_list(LOGTAG_INPUT_CANCEL)
3946 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3947
hongzuo liu95785e22022-09-06 02:51:35 +00003948 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003949 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003950 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00003951 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003952
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003953 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003954 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003955 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003956
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003957 switch (cancelationEventEntry->type) {
3958 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003959 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00003960 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
3961 ? std::make_optional(keyEntry.displayId)
3962 : std::nullopt;
3963 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003964 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
3965 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003966 } else {
3967 targets.emplace_back(fallbackTarget);
3968 }
3969 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003970 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003972 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003973 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00003974 const std::optional<int32_t> targetDisplay =
3975 motionEntry.displayId != ADISPLAY_ID_NONE
3976 ? std::make_optional(motionEntry.displayId)
3977 : std::nullopt;
3978 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003979 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003980 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003981 pointerIndex++) {
3982 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
3983 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00003984 if (mDragState && mDragState->dragWindow->getToken() == token &&
3985 pointerIds.test(mDragState->pointerId)) {
3986 LOG(INFO) << __func__
3987 << ": Canceling drag and drop because the pointers for the drag "
3988 "window are being canceled.";
3989 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3990 mDragState.reset();
3991 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003992 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
3993 ftl::Flags<InputTarget::Flags>(), pointerIds,
3994 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003995 } else {
3996 targets.emplace_back(fallbackTarget);
3997 const auto it = mDisplayInfos.find(motionEntry.displayId);
3998 if (it != mDisplayInfos.end()) {
3999 targets.back().displayTransform = it->second.transform;
4000 targets.back().setDefaultPointerTransform(it->second.transform);
4001 }
4002 }
4003 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004004 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004006 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004007 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004008 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4009 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004010 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004011 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004012 break;
4013 }
4014 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004015 case EventEntry::Type::DEVICE_RESET:
4016 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004017 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004018 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004019 break;
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
4022
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004023 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004024 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004026
hongzuo liu95785e22022-09-06 02:51:35 +00004027 // If the outbound queue was previously empty, start the dispatch cycle going.
4028 if (wasEmpty && !connection->outboundQueue.empty()) {
4029 startDispatchCycleLocked(currentTime, connection);
4030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031}
4032
Svet Ganov5d3bc372020-01-26 23:11:07 -08004033void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004034 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004035 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004036 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004037 return;
4038 }
4039
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004040 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004041 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042
4043 if (downEvents.empty()) {
4044 return;
4045 }
4046
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004047 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004048 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4049 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004050 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004051
chaviw98318de2021-05-19 16:45:23 -05004052 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004053 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054
hongzuo liu95785e22022-09-06 02:51:35 +00004055 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004056 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004057 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004058 switch (downEventEntry->type) {
4059 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004060 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4061 if (windowHandle != nullptr) {
4062 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004063 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004064 pointerIndex++) {
4065 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4066 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004067 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4068 targetFlags, pointerIds, motionEntry.downTime,
4069 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004070 } else {
4071 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4072 .flags = targetFlags});
4073 const auto it = mDisplayInfos.find(motionEntry.displayId);
4074 if (it != mDisplayInfos.end()) {
4075 targets.back().displayTransform = it->second.transform;
4076 targets.back().setDefaultPointerTransform(it->second.transform);
4077 }
4078 }
4079 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004080 break;
4081 }
4082
4083 case EventEntry::Type::KEY:
4084 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004085 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004086 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004087 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004088 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004089 case EventEntry::Type::SENSOR:
4090 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004091 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004092 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004093 break;
4094 }
4095 }
4096
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004097 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004098 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004099 }
4100
hongzuo liu95785e22022-09-06 02:51:35 +00004101 // If the outbound queue was previously empty, start the dispatch cycle going.
4102 if (wasEmpty && !connection->outboundQueue.empty()) {
4103 startDispatchCycleLocked(downTime, connection);
4104 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004105}
4106
Arthur Hungc539dbb2022-12-08 07:45:36 +00004107void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4108 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4109 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004110 std::shared_ptr<Connection> wallpaperConnection =
4111 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004112 if (wallpaperConnection != nullptr) {
4113 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4114 }
4115 }
4116}
4117
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004119 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4120 nsecs_t splitDownTime) {
4121 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
4123 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004124 std::vector<PointerProperties> splitPointerProperties;
4125 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004127 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 uint32_t splitPointerCount = 0;
4129
4130 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004133 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004135 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004137 splitPointerProperties.push_back(pointerProperties);
4138 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 splitPointerCount += 1;
4140 }
4141 }
4142
4143 if (splitPointerCount != pointerIds.count()) {
4144 // This is bad. We are missing some of the pointers that we expected to deliver.
4145 // Most likely this indicates that we received an ACTION_MOVE events that has
4146 // different pointer ids than we expected based on the previous ACTION_DOWN
4147 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4148 // in this way.
4149 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004150 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004151 "a broken sequence of pointer ids from the input device: %s",
4152 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004153 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 }
4155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004156 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004158 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4159 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004160 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004162 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004164 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 if (pointerIds.count() == 1) {
4166 // The first/last pointer went down/up.
4167 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004169 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4170 ? AMOTION_EVENT_ACTION_CANCEL
4171 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 } else {
4173 // A secondary pointer went down/up.
4174 uint32_t splitPointerIndex = 0;
4175 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4176 splitPointerIndex += 1;
4177 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 action = maskedAction |
4179 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181 } else {
4182 // An unrelated pointer changed.
4183 action = AMOTION_EVENT_ACTION_MOVE;
4184 }
4185 }
4186
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004187 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4188 logDispatchStateLocked();
4189 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4190 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4191 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004192 }
4193
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004194 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004195 ATRACE_NAME_IF(ATRACE_ENABLED(),
4196 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4197 ").",
4198 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004199 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004200 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4201 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004202 originalMotionEntry.deviceId, originalMotionEntry.source,
4203 originalMotionEntry.displayId,
4204 originalMotionEntry.policyFlags, action,
4205 originalMotionEntry.actionButton,
4206 originalMotionEntry.flags, originalMotionEntry.metaState,
4207 originalMotionEntry.buttonState,
4208 originalMotionEntry.classification,
4209 originalMotionEntry.edgeFlags,
4210 originalMotionEntry.xPrecision,
4211 originalMotionEntry.yPrecision,
4212 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004213 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004214 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 return splitMotionEntry;
4217}
4218
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004219void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4220 std::scoped_lock _l(mLock);
4221 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4222}
4223
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004224void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004225 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004226 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
Antonio Kantekf16f2832021-09-28 04:39:20 +00004229 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004231 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004234 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004235 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 } // release lock
4237
4238 if (needWake) {
4239 mLooper->wake();
4240 }
4241}
4242
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004243void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004244 ALOGD_IF(debugInboundEventDetails(),
4245 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4246 ", deviceId=%d, source=%s, displayId=%" PRId32
4247 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4248 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004249 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4250 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4251 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004252 Result<void> keyCheck = validateKeyEvent(args.action);
4253 if (!keyCheck.ok()) {
4254 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 return;
4256 }
4257
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004258 uint32_t policyFlags = args.policyFlags;
4259 int32_t flags = args.flags;
4260 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004261 // InputDispatcher tracks and generates key repeats on behalf of
4262 // whatever notifies it, so repeatCount should always be set to 0
4263 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4265 policyFlags |= POLICY_FLAG_VIRTUAL;
4266 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 if (policyFlags & POLICY_FLAG_FUNCTION) {
4269 metaState |= AMETA_FUNCTION_ON;
4270 }
4271
4272 policyFlags |= POLICY_FLAG_TRUSTED;
4273
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004274 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004276 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4277 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4278 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
Michael Wright2b3c3302018-03-02 17:19:13 +00004280 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004281 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004282 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4283 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
Antonio Kantekf16f2832021-09-28 04:39:20 +00004287 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 { // acquire lock
4289 mLock.lock();
4290
4291 if (shouldSendKeyToInputFilterLocked(args)) {
4292 mLock.unlock();
4293
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004294 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004295 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 return; // event was consumed by the filter
4297 }
4298
4299 mLock.lock();
4300 }
4301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004302 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004303 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4304 args.deviceId, args.source, args.displayId, policyFlags,
4305 args.action, flags, keyCode, args.scanCode, metaState,
4306 repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004308 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 mLock.unlock();
4310 } // release lock
4311
4312 if (needWake) {
4313 mLooper->wake();
4314 }
4315}
4316
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004317bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 return mInputFilterEnabled;
4319}
4320
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004321void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004322 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004323 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004324 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004325 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004326 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4327 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004328 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4329 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4330 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4331 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4332 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004333 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004334 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4335 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004336 i, args.pointerProperties[i].id,
4337 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4338 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4339 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4340 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4341 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4342 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4343 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4344 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4345 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4346 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004349
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004350 Result<void> motionCheck =
4351 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4352 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004353 if (!motionCheck.ok()) {
4354 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4355 return;
4356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004358 if (DEBUG_VERIFY_EVENTS) {
4359 auto [it, _] =
4360 mVerifiersByDisplay.try_emplace(args.displayId,
4361 StringPrintf("display %" PRId32, args.displayId));
4362 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004363 it->second.processMovement(args.deviceId, args.source, args.action,
4364 args.getPointerCount(), args.pointerProperties.data(),
4365 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004366 if (!result.ok()) {
4367 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4368 }
4369 }
4370
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004371 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004373
4374 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004375 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4376 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004377 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4378 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004379 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
Antonio Kantekf16f2832021-09-28 04:39:20 +00004382 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 { // acquire lock
4384 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004385 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4386 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4387 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004388 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004389 if (touchStateIt != mTouchStatesByDisplay.end()) {
4390 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004391 if (touchState.hasTouchingPointers(args.deviceId) ||
4392 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004393 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4394 }
4395 }
4396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397
4398 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004399 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004401 displayTransform = it->second.transform;
4402 }
4403
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 mLock.unlock();
4405
4406 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004407 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4408 args.action, args.actionButton, args.flags, args.edgeFlags,
4409 args.metaState, args.buttonState, args.classification,
4410 displayTransform, args.xPrecision, args.yPrecision,
4411 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004412 args.downTime, args.eventTime, args.getPointerCount(),
4413 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
4415 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004416 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 return; // event was consumed by the filter
4418 }
4419
4420 mLock.lock();
4421 }
4422
4423 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004424 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004425 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4426 args.deviceId, args.source, args.displayId,
4427 policyFlags, args.action, args.actionButton,
4428 args.flags, args.metaState, args.buttonState,
4429 args.classification, args.edgeFlags, args.xPrecision,
4430 args.yPrecision, args.xCursorPosition,
4431 args.yCursorPosition, args.downTime,
4432 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004434 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4435 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004436 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004437 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004438 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4439 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4440 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004441 }
4442
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004443 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 mLock.unlock();
4445 } // release lock
4446
4447 if (needWake) {
4448 mLooper->wake();
4449 }
4450}
4451
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004452void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004453 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004454 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4455 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004456 args.id, args.eventTime, args.deviceId, args.source,
4457 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004458 }
Chris Yef59a2f42020-10-16 12:55:26 -07004459
Antonio Kantekf16f2832021-09-28 04:39:20 +00004460 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004461 { // acquire lock
4462 mLock.lock();
4463
4464 // Just enqueue a new sensor event.
4465 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004466 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4467 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4468 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004469
4470 needWake = enqueueInboundEventLocked(std::move(newEntry));
4471 mLock.unlock();
4472 } // release lock
4473
4474 if (needWake) {
4475 mLooper->wake();
4476 }
4477}
4478
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004479void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004480 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4482 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004483 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004484 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004485}
4486
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004488 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489}
4490
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004491void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004492 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004493 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4494 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004495 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004498 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004500 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501}
4502
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004503void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004504 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004505 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4506 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Antonio Kantekf16f2832021-09-28 04:39:20 +00004509 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004511 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004513 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004514 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004515 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004516
4517 for (auto& [_, verifier] : mVerifiersByDisplay) {
4518 verifier.resetDevice(args.deviceId);
4519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 } // release lock
4521
4522 if (needWake) {
4523 mLooper->wake();
4524 }
4525}
4526
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004527void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004528 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004529 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4530 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004531 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004532
Antonio Kantekf16f2832021-09-28 04:39:20 +00004533 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004534 { // acquire lock
4535 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004536 auto entry =
4537 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004538 needWake = enqueueInboundEventLocked(std::move(entry));
4539 } // release lock
4540
4541 if (needWake) {
4542 mLooper->wake();
4543 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004544}
4545
Prabir Pradhan5735a322022-04-11 17:23:34 +00004546InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004547 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004548 InputEventInjectionSync syncMode,
4549 std::chrono::milliseconds timeout,
4550 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004551 Result<void> eventValidation = validateInputEvent(*event);
4552 if (!eventValidation.ok()) {
4553 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4554 return InputEventInjectionResult::FAILED;
4555 }
4556
Prabir Pradhan65613802023-02-22 23:36:58 +00004557 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004558 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4559 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4560 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4561 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004562 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004563 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564
Prabir Pradhan5735a322022-04-11 17:23:34 +00004565 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004567 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004568 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4569 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4570 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4571 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4572 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004573 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004574 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004575 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004576 }
4577
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004578 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4579 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004581 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004583 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004584 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004585 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004586 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004587 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4588 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4589 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004590 int32_t keyCode = incomingKey.getKeyCode();
4591 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004592 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004593 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004594 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4595 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4596 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004598 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4599 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004600 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004601
4602 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4603 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004604 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004605 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4606 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4607 std::to_string(t.duration().count()).c_str());
4608 }
4609 }
4610
4611 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004612 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004613 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4614 incomingKey.getEventTime(), resolvedDeviceId,
4615 incomingKey.getSource(), incomingKey.getDisplayId(),
4616 policyFlags, action, flags, keyCode,
4617 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004618 incomingKey.getRepeatCount(),
4619 incomingKey.getDownTime());
4620 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622 }
4623
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004624 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004625 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004626 const bool isPointerEvent =
4627 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4628 // If a pointer event has no displayId specified, inject it to the default display.
4629 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4630 ? ADISPLAY_ID_DEFAULT
4631 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004632 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633
4634 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004635 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004636 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004637 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4638 motionEvent.getAction(), eventTime,
4639 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4641 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4642 std::to_string(t.duration().count()).c_str());
4643 }
4644 }
4645
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004646 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4647 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4648 }
4649
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004652 const size_t pointerCount = motionEvent.getPointerCount();
4653 const std::vector<PointerProperties>
4654 pointerProperties(motionEvent.getPointerProperties(),
4655 motionEvent.getPointerProperties() + pointerCount);
4656
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004657 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004659 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4660 *sampleEventTimes, resolvedDeviceId,
4661 motionEvent.getSource(), displayId, policyFlags,
4662 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004663 motionEvent.getActionButton(), flags,
4664 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004665 motionEvent.getButtonState(),
4666 motionEvent.getClassification(),
4667 motionEvent.getEdgeFlags(),
4668 motionEvent.getXPrecision(),
4669 motionEvent.getYPrecision(),
4670 motionEvent.getRawXCursorPosition(),
4671 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004672 motionEvent.getDownTime(), pointerProperties,
4673 std::vector<PointerCoords>(samplePointerCoords,
4674 samplePointerCoords +
4675 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004676 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004677 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004678 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004680 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004681 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004682 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4683 resolvedDeviceId, motionEvent.getSource(), displayId,
4684 policyFlags, motionEvent.getAction(),
4685 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004686 motionEvent.getMetaState(), motionEvent.getButtonState(),
4687 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4688 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4689 motionEvent.getRawXCursorPosition(),
4690 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4691 pointerProperties,
4692 std::vector<PointerCoords>(samplePointerCoords,
4693 samplePointerCoords +
4694 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004695 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4696 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004697 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004698 }
4699 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004702 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004703 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004704 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 }
4706
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004708 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004709 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004710 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004711 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004712 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004713 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 }
4715
4716 mLock.unlock();
4717
4718 if (needWake) {
4719 mLooper->wake();
4720 }
4721
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004722 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004724 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 if (syncMode == InputEventInjectionSync::NONE) {
4727 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 } else {
4729 for (;;) {
4730 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004731 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 break;
4733 }
4734
4735 nsecs_t remainingTimeout = endTime - now();
4736 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004737 if (DEBUG_INJECTION) {
4738 ALOGD("injectInputEvent - Timed out waiting for injection result "
4739 "to become available.");
4740 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 break;
4743 }
4744
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004745 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 }
4747
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004748 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4749 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004751 if (DEBUG_INJECTION) {
4752 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4753 injectionState->pendingForegroundDispatches);
4754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 nsecs_t remainingTimeout = endTime - now();
4756 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004757 if (DEBUG_INJECTION) {
4758 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4759 "dispatches to finish.");
4760 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004761 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 break;
4763 }
4764
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004765 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 }
4767 }
4768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 } // release lock
4770
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004771 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004772 LOG(INFO) << "injectInputEvent - Finished with result "
4773 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
4776 return injectionResult;
4777}
4778
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004779std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004780 std::array<uint8_t, 32> calculatedHmac;
4781 std::unique_ptr<VerifiedInputEvent> result;
4782 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004783 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004784 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4785 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4786 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004787 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004788 break;
4789 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004790 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004791 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4792 VerifiedMotionEvent verifiedMotionEvent =
4793 verifiedMotionEventFromMotionEvent(motionEvent);
4794 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004795 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004796 break;
4797 }
4798 default: {
4799 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4800 return nullptr;
4801 }
4802 }
4803 if (calculatedHmac == INVALID_HMAC) {
4804 return nullptr;
4805 }
tyiu1573a672023-02-21 22:38:32 +00004806 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004807 return nullptr;
4808 }
4809 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004810}
4811
Prabir Pradhan24047542023-11-02 17:14:59 +00004812void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004814 if (!entry.injectionState) {
4815 // Not an injected event.
4816 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004818
4819 InjectionState& injectionState = *entry.injectionState;
4820 if (DEBUG_INJECTION) {
4821 LOG(INFO) << "Setting input event injection result to "
4822 << ftl::enum_string(injectionResult);
4823 }
4824
4825 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4826 // Log the outcome since the injector did not wait for the injection result.
4827 switch (injectionResult) {
4828 case InputEventInjectionResult::SUCCEEDED:
4829 ALOGV("Asynchronous input event injection succeeded.");
4830 break;
4831 case InputEventInjectionResult::TARGET_MISMATCH:
4832 ALOGV("Asynchronous input event injection target mismatch.");
4833 break;
4834 case InputEventInjectionResult::FAILED:
4835 ALOGW("Asynchronous input event injection failed.");
4836 break;
4837 case InputEventInjectionResult::TIMED_OUT:
4838 ALOGW("Asynchronous input event injection timed out.");
4839 break;
4840 case InputEventInjectionResult::PENDING:
4841 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4842 break;
4843 }
4844 }
4845
4846 injectionState.injectionResult = injectionResult;
4847 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848}
4849
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004850void InputDispatcher::transformMotionEntryForInjectionLocked(
4851 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004852 // Input injection works in the logical display coordinate space, but the input pipeline works
4853 // display space, so we need to transform the injected events accordingly.
4854 const auto it = mDisplayInfos.find(entry.displayId);
4855 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004856 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004857
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004858 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4859 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4860 const vec2 cursor =
4861 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4862 {entry.xCursorPosition, entry.yCursorPosition});
4863 entry.xCursorPosition = cursor.x;
4864 entry.yCursorPosition = cursor.y;
4865 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004866 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004867 entry.pointerCoords[i] =
4868 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4869 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004870 }
4871}
4872
Prabir Pradhan24047542023-11-02 17:14:59 +00004873void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004874 if (entry.injectionState) {
4875 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877}
4878
Prabir Pradhan24047542023-11-02 17:14:59 +00004879void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004880 if (entry.injectionState) {
4881 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004883 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004884 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 }
4886 }
4887}
4888
chaviw98318de2021-05-19 16:45:23 -05004889const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004890 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004891 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004892 auto it = mWindowHandlesByDisplay.find(displayId);
4893 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004894}
4895
chaviw98318de2021-05-19 16:45:23 -05004896sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004897 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004898 if (windowHandleToken == nullptr) {
4899 return nullptr;
4900 }
4901
Prabir Pradhan16463382023-10-12 23:03:19 +00004902 if (!displayId) {
4903 // Look through all displays.
4904 for (auto& it : mWindowHandlesByDisplay) {
4905 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4906 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4907 if (windowHandle->getToken() == windowHandleToken) {
4908 return windowHandle;
4909 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004912 return nullptr;
4913 }
4914
Prabir Pradhan16463382023-10-12 23:03:19 +00004915 // Only look through the requested display.
4916 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004917 if (windowHandle->getToken() == windowHandleToken) {
4918 return windowHandle;
4919 }
4920 }
4921 return nullptr;
4922}
4923
chaviw98318de2021-05-19 16:45:23 -05004924sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4925 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004926 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004927 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4928 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004929 if (handle->getId() == windowHandle->getId() &&
4930 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004931 if (windowHandle->getInfo()->displayId != it.first) {
4932 ALOGE("Found window %s in display %" PRId32
4933 ", but it should belong to display %" PRId32,
4934 windowHandle->getName().c_str(), it.first,
4935 windowHandle->getInfo()->displayId);
4936 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004937 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 }
4940 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004941 return nullptr;
4942}
4943
chaviw98318de2021-05-19 16:45:23 -05004944sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004945 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4946 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947}
4948
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004949ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4950 auto displayInfoIt = mDisplayInfos.find(displayId);
4951 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4952 : kIdentityTransform;
4953}
4954
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004955bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4956 const MotionEntry& motionEntry) const {
4957 const WindowInfo& info = *window->getInfo();
4958
4959 // Skip spy window targets that are not valid for targeted injection.
4960 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004961 return false;
4962 }
4963
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004964 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4965 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4966 return false;
4967 }
4968
4969 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4970 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4971 window->getName().c_str());
4972 return false;
4973 }
4974
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004975 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004976 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004977 ALOGW("Not sending touch to %s because there's no corresponding connection",
4978 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004979 return false;
4980 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004981
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004982 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004983 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004984 return false;
4985 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004986
4987 // Drop events that can't be trusted due to occlusion
4988 const auto [x, y] = resolveTouchedPosition(motionEntry);
4989 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4990 if (!isTouchTrustedLocked(occlusionInfo)) {
4991 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004992 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004993 for (const auto& log : occlusionInfo.debugInfo) {
4994 ALOGD("%s", log.c_str());
4995 }
4996 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004997 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4998 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004999 return false;
5000 }
5001
5002 // Drop touch events if requested by input feature
5003 if (shouldDropInput(motionEntry, window)) {
5004 return false;
5005 }
5006
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005007 // Ignore touches if stylus is down anywhere on screen
5008 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5009 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5010 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5011 return false;
5012 }
5013
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005014 return true;
5015}
5016
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005017std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5018 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005019 auto connectionIt = mConnectionsByToken.find(token);
5020 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005021 return nullptr;
5022 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005023 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005024}
5025
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005026void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005027 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5028 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005029 // Remove all handles on a display if there are no windows left.
5030 mWindowHandlesByDisplay.erase(displayId);
5031 return;
5032 }
5033
5034 // Since we compare the pointer of input window handles across window updates, we need
5035 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005036 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5037 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5038 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005039 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005040 }
5041
chaviw98318de2021-05-19 16:45:23 -05005042 std::vector<sp<WindowInfoHandle>> newHandles;
5043 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005044 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005045 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005046 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005047 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005048 const bool canReceiveInput =
5049 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5050 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005051 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005052 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005053 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005054 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005055 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005056 }
5057
5058 if (info->displayId != displayId) {
5059 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5060 handle->getName().c_str(), displayId, info->displayId);
5061 continue;
5062 }
5063
Robert Carredd13602020-04-13 17:24:34 -07005064 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5065 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005066 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005067 oldHandle->updateFrom(handle);
5068 newHandles.push_back(oldHandle);
5069 } else {
5070 newHandles.push_back(handle);
5071 }
5072 }
5073
5074 // Insert or replace
5075 mWindowHandlesByDisplay[displayId] = newHandles;
5076}
5077
Arthur Hungb92218b2018-08-14 12:00:21 +08005078/**
5079 * Called from InputManagerService, update window handle list by displayId that can receive input.
5080 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5081 * If set an empty list, remove all handles from the specific display.
5082 * For focused handle, check if need to change and send a cancel event to previous one.
5083 * For removed handle, check if need to send a cancel event if already in touch.
5084 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005085void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005086 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005087 if (DEBUG_FOCUS) {
5088 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005089 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 windowList += iwh->getName() + " ";
5091 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005092 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094
Prabir Pradhand65552b2021-10-07 11:23:50 -07005095 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005096 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005097 const WindowInfo& info = *window->getInfo();
5098
5099 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005100 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005101 if (noInputWindow && window->getToken() != nullptr) {
5102 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5103 window->getName().c_str());
5104 window->releaseChannel();
5105 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005106
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005107 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005108 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5109 !info.inputConfig.test(
5110 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005111 "%s has feature SPY, but is not a trusted overlay.",
5112 window->getName().c_str());
5113
Prabir Pradhand65552b2021-10-07 11:23:50 -07005114 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005115 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5116 !info.inputConfig.test(
5117 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005118 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5119 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005120 }
5121
Arthur Hung72d8dc32020-03-28 00:48:39 +00005122 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005123 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
chaviw98318de2021-05-19 16:45:23 -05005125 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005126
chaviw98318de2021-05-19 16:45:23 -05005127 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005128
Vishnu Nairc519ff72021-01-21 08:23:08 -08005129 std::optional<FocusResolver::FocusChanges> changes =
5130 mFocusResolver.setInputWindows(displayId, windowHandles);
5131 if (changes) {
5132 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005135 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5136 mTouchStatesByDisplay.find(displayId);
5137 if (stateIt != mTouchStatesByDisplay.end()) {
5138 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005139 for (size_t i = 0; i < state.windows.size();) {
5140 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005141 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005142 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5143 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005144 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005145 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5146 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005147 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005148 "touched window was removed");
5149 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005150 // Since we are about to drop the touch, cancel the events for the wallpaper as
5151 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005152 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005153 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5154 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005155 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005156 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005159 state.windows.erase(state.windows.begin() + i);
5160 } else {
5161 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163 }
arthurhungb89ccb02020-12-30 16:19:01 +08005164
arthurhung6d4bed92021-03-17 11:59:33 +08005165 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005166 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005167 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005168 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005169 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005170 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5171 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005172 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005173 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005174 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005175
Arthur Hung72d8dc32020-03-28 00:48:39 +00005176 // Release information for windows that are no longer present.
5177 // This ensures that unused input channels are released promptly.
5178 // Otherwise, they might stick around until the window handle is destroyed
5179 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005180 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005181 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005182 if (DEBUG_FOCUS) {
5183 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005184 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005185 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005186 }
chaviw291d88a2019-02-14 10:33:58 -08005187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188}
5189
5190void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005191 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005192 if (DEBUG_FOCUS) {
5193 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5194 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5195 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005196 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005197 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005198 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199 } // release lock
5200
5201 // Wake up poll loop since it may need to make new input dispatching choices.
5202 mLooper->wake();
5203}
5204
Vishnu Nair599f1412021-06-21 10:39:58 -07005205void InputDispatcher::setFocusedApplicationLocked(
5206 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5207 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5208 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5209
5210 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5211 return; // This application is already focused. No need to wake up or change anything.
5212 }
5213
5214 // Set the new application handle.
5215 if (inputApplicationHandle != nullptr) {
5216 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5217 } else {
5218 mFocusedApplicationHandlesByDisplay.erase(displayId);
5219 }
5220
5221 // No matter what the old focused application was, stop waiting on it because it is
5222 // no longer focused.
5223 resetNoFocusedWindowTimeoutLocked();
5224}
5225
Tiger Huang721e26f2018-07-24 22:26:19 +08005226/**
5227 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5228 * the display not specified.
5229 *
5230 * We track any unreleased events for each window. If a window loses the ability to receive the
5231 * released event, we will send a cancel event to it. So when the focused display is changed, we
5232 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5233 * display. The display-specified events won't be affected.
5234 */
5235void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005236 if (DEBUG_FOCUS) {
5237 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5238 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005239 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005240 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005241
5242 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005243 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005244 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005245 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005246 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005247 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005248 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005249 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005250 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005251 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005252 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005253 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5254 }
5255 }
5256 mFocusedDisplayId = displayId;
5257
Chris Ye3c2d6f52020-08-09 10:39:48 -07005258 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005259 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005260 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005261
Vishnu Nairad321cd2020-08-20 16:40:21 -07005262 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005263 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005264 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005265 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005266 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 }
5268 }
5269 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005270 } // release lock
5271
5272 // Wake up poll loop since it may need to make new input dispatching choices.
5273 mLooper->wake();
5274}
5275
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005277 if (DEBUG_FOCUS) {
5278 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280
5281 bool changed;
5282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
5285 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5286 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005287 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
5289
5290 if (mDispatchEnabled && !enabled) {
5291 resetAndDropEverythingLocked("dispatcher is being disabled");
5292 }
5293
5294 mDispatchEnabled = enabled;
5295 mDispatchFrozen = frozen;
5296 changed = true;
5297 } else {
5298 changed = false;
5299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 } // release lock
5301
5302 if (changed) {
5303 // Wake up poll loop since it may need to make new input dispatching choices.
5304 mLooper->wake();
5305 }
5306}
5307
5308void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005309 if (DEBUG_FOCUS) {
5310 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
5313 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005314 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315
5316 if (mInputFilterEnabled == enabled) {
5317 return;
5318 }
5319
5320 mInputFilterEnabled = enabled;
5321 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5322 } // release lock
5323
5324 // Wake up poll loop since there might be work to do to drop everything.
5325 mLooper->wake();
5326}
5327
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005328bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005329 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005330 bool needWake = false;
5331 {
5332 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005333 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005334 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005335 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005336 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5337 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005338 mTouchModePerDisplay.count(displayId) == 0
5339 ? "not set"
5340 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5341
Antonio Kantek15beb512022-06-13 22:35:41 +00005342 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5343 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005344 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005345 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005346 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005347 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5348 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005349 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005350 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005351 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005352 return false;
5353 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005354 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005355 mTouchModePerDisplay[displayId] = inTouchMode;
5356 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5357 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005358 needWake = enqueueInboundEventLocked(std::move(entry));
5359 } // release lock
5360
5361 if (needWake) {
5362 mLooper->wake();
5363 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005364 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005365}
5366
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005367bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005368 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5369 if (focusedToken == nullptr) {
5370 return false;
5371 }
5372 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5373 return isWindowOwnedBy(windowHandle, pid, uid);
5374}
5375
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005376bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005377 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5378 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5379 const sp<WindowInfoHandle> windowHandle =
5380 getWindowHandleLocked(connectionToken);
5381 return isWindowOwnedBy(windowHandle, pid, uid);
5382 }) != mInteractionConnectionTokens.end();
5383}
5384
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005385void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5386 if (opacity < 0 || opacity > 1) {
5387 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5388 return;
5389 }
5390
5391 std::scoped_lock lock(mLock);
5392 mMaximumObscuringOpacityForTouch = opacity;
5393}
5394
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005395std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5396InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005397 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5398 for (TouchedWindow& w : state.windows) {
5399 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005400 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005401 }
5402 }
5403 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005404 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005405}
5406
arthurhungb89ccb02020-12-30 16:19:01 +08005407bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5408 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005409 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005410 if (DEBUG_FOCUS) {
5411 ALOGD("Trivial transfer to same window.");
5412 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005413 return true;
5414 }
5415
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
Arthur Hungabbb9d82021-09-01 14:52:30 +00005419 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005420 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005421
Arthur Hungabbb9d82021-09-01 14:52:30 +00005422 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005423 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 return false;
5425 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005426 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5427 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005428 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5429 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005430 return false;
5431 }
5432 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005433
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5435 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005436 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005437 return false;
5438 }
5439
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005440 if (DEBUG_FOCUS) {
5441 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005442 touchedWindow->windowHandle->getName().c_str(),
5443 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 }
5445
Arthur Hungabbb9d82021-09-01 14:52:30 +00005446 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005447 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005448 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005449 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005450 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005453 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005454 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005455 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005456 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005457 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005458 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005459 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005460 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
Arthur Hungabbb9d82021-09-01 14:52:30 +00005462 // Store the dragging window.
5463 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005464 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005465 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5466 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005467 return false;
5468 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005469 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005470 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005471 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 }
5473
Arthur Hungabbb9d82021-09-01 14:52:30 +00005474 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005475 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5476 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005477 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005478 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005479 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5480 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005482 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5483 newTargetFlags);
5484
5485 // Check if the wallpaper window should deliver the corresponding event.
5486 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005487 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489 } // release lock
5490
5491 // Wake up poll loop since it may need to make new input dispatching choices.
5492 mLooper->wake();
5493 return true;
5494}
5495
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005496/**
5497 * Get the touched foreground window on the given display.
5498 * Return null if there are no windows touched on that display, or if more than one foreground
5499 * window is being touched.
5500 */
5501sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5502 auto stateIt = mTouchStatesByDisplay.find(displayId);
5503 if (stateIt == mTouchStatesByDisplay.end()) {
5504 ALOGI("No touch state on display %" PRId32, displayId);
5505 return nullptr;
5506 }
5507
5508 const TouchState& state = stateIt->second;
5509 sp<WindowInfoHandle> touchedForegroundWindow;
5510 // If multiple foreground windows are touched, return nullptr
5511 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005512 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005513 if (touchedForegroundWindow != nullptr) {
5514 ALOGI("Two or more foreground windows: %s and %s",
5515 touchedForegroundWindow->getName().c_str(),
5516 window.windowHandle->getName().c_str());
5517 return nullptr;
5518 }
5519 touchedForegroundWindow = window.windowHandle;
5520 }
5521 }
5522 return touchedForegroundWindow;
5523}
5524
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005525// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005526bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005527 sp<IBinder> fromToken;
5528 { // acquire lock
5529 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005530 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005531 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005532 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5533 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005534 return false;
5535 }
5536
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005537 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5538 if (from == nullptr) {
5539 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5540 return false;
5541 }
5542
5543 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005544 } // release lock
5545
5546 return transferTouchFocus(fromToken, destChannelToken);
5547}
5548
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005550 if (DEBUG_FOCUS) {
5551 ALOGD("Resetting and dropping all events (%s).", reason);
5552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553
Michael Wrightfb04fd52022-11-24 22:31:11 +00005554 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 synthesizeCancelationEventsForAllConnectionsLocked(options);
5556
5557 resetKeyRepeatLocked();
5558 releasePendingEventLocked();
5559 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005563 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564}
5565
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005566void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005567 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 dumpDispatchStateLocked(dump);
5569
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005570 std::istringstream stream(dump);
5571 std::string line;
5572
5573 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005574 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 }
5576}
5577
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005578std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005579 std::string dump;
5580
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005581 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5582 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005583
5584 std::string windowName = "None";
5585 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005586 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005587 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5588 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5589 : "token has capture without window";
5590 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005591 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005592
5593 return dump;
5594}
5595
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005596void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005597 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5598 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5599 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005600 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601
Tiger Huang721e26f2018-07-24 22:26:19 +08005602 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5603 dump += StringPrintf(INDENT "FocusedApplications:\n");
5604 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5605 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005606 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005607 const std::chrono::duration timeout =
5608 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005610 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005611 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005614 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005616
Vishnu Nairc519ff72021-01-21 08:23:08 -08005617 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005618 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005620 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005621 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005622 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005623 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5624 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 }
5626 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005627 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 }
5629
arthurhung6d4bed92021-03-17 11:59:33 +08005630 if (mDragState) {
5631 dump += StringPrintf(INDENT "DragState:\n");
5632 mDragState->dump(dump, INDENT2);
5633 }
5634
Arthur Hungb92218b2018-08-14 12:00:21 +08005635 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005636 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5637 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5638 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5639 const auto& displayInfo = it->second;
5640 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5641 displayInfo.logicalHeight);
5642 displayInfo.transform.dump(dump, "transform", INDENT4);
5643 } else {
5644 dump += INDENT2 "No DisplayInfo found!\n";
5645 }
5646
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005647 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005648 dump += INDENT2 "Windows:\n";
5649 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005650 dump += StringPrintf(INDENT3 "%zu: %s", i,
5651 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005652 }
5653 } else {
5654 dump += INDENT2 "Windows: <none>\n";
5655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 }
5657 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005658 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 }
5660
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 if (!mGlobalMonitorsByDisplay.empty()) {
5662 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5663 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005664 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005667 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668 }
5669
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005670 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671
5672 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005673 if (!mRecentQueue.empty()) {
5674 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005675 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005676 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005677 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005678 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 }
5680 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005681 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 }
5683
5684 // Dump event currently being dispatched.
5685 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005686 dump += INDENT "PendingEvent:\n";
5687 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005688 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005689 dump += StringPrintf(", age=%" PRId64 "ms\n",
5690 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005692 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 }
5694
5695 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005696 if (!mInboundQueue.empty()) {
5697 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005698 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005699 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005700 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005701 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 }
5703 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005704 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
5706
Prabir Pradhancef936d2021-07-21 16:17:52 +00005707 if (!mCommandQueue.empty()) {
5708 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5709 } else {
5710 dump += INDENT "CommandQueue: <empty>\n";
5711 }
5712
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005713 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005714 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005715 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005716 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005717 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005718 connection->inputChannel->getFd().get(),
5719 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005720 connection->getWindowName().c_str(),
5721 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005724 if (!connection->outboundQueue.empty()) {
5725 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5726 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005727 dump += dumpQueue(connection->outboundQueue, currentTime);
5728
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005730 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 }
5732
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005733 if (!connection->waitQueue.empty()) {
5734 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5735 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005736 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005738 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005740 std::string inputStateDump = streamableToString(connection->inputState);
5741 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005742 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005743 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745 }
5746 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005747 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 }
5749
Antonio Kantek15beb512022-06-13 22:35:41 +00005750 if (!mTouchModePerDisplay.empty()) {
5751 dump += INDENT "TouchModePerDisplay:\n";
5752 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5753 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5754 std::to_string(touchMode).c_str());
5755 }
5756 } else {
5757 dump += INDENT "TouchModePerDisplay: <none>\n";
5758 }
5759
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005760 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005761 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5762 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5763 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005764 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005765 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766}
5767
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005768void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005769 const size_t numMonitors = monitors.size();
5770 for (size_t i = 0; i < numMonitors; i++) {
5771 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005772 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005773 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5774 dump += "\n";
5775 }
5776}
5777
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005778class LooperEventCallback : public LooperCallback {
5779public:
5780 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5781 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5782
5783private:
5784 std::function<int(int events)> mCallback;
5785};
5786
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005787Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005788 if (DEBUG_CHANNEL_CREATION) {
5789 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005792 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005793 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005794 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005795
5796 if (result) {
5797 return base::Error(result) << "Failed to open input channel pair with name " << name;
5798 }
5799
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005801 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005802 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005803 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005804 std::shared_ptr<Connection> connection =
5805 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5806 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005808 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5809 ALOGE("Created a new connection, but the token %p is already known", token.get());
5810 }
5811 mConnectionsByToken.emplace(token, connection);
5812
5813 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5814 this, std::placeholders::_1, token);
5815
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005816 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005817 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818 } // release lock
5819
5820 // Wake the looper because some connections have changed.
5821 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005822 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823}
5824
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005825Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005826 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005827 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005828 std::shared_ptr<InputChannel> serverChannel;
5829 std::unique_ptr<InputChannel> clientChannel;
5830 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5831 if (result) {
5832 return base::Error(result) << "Failed to open input channel pair with name " << name;
5833 }
5834
Michael Wright3dd60e22019-03-27 22:06:44 +00005835 { // acquire lock
5836 std::scoped_lock _l(mLock);
5837
5838 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005839 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5840 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005841 }
5842
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005843 std::shared_ptr<Connection> connection =
5844 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005845 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005846 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005847
5848 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5849 ALOGE("Created a new connection, but the token %p is already known", token.get());
5850 }
5851 mConnectionsByToken.emplace(token, connection);
5852 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5853 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005854
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005855 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005856
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005857 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005858 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005859 }
Garfield Tan15601662020-09-22 15:32:38 -07005860
Michael Wright3dd60e22019-03-27 22:06:44 +00005861 // Wake the looper because some connections have changed.
5862 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005863 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005864}
5865
Garfield Tan15601662020-09-22 15:32:38 -07005866status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005868 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869
Harry Cutts33476232023-01-30 19:57:29 +00005870 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871 if (status) {
5872 return status;
5873 }
5874 } // release lock
5875
5876 // Wake the poll loop because removing the connection may have changed the current
5877 // synchronization state.
5878 mLooper->wake();
5879 return OK;
5880}
5881
Garfield Tan15601662020-09-22 15:32:38 -07005882status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5883 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005884 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005885 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005886 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887 return BAD_VALUE;
5888 }
5889
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005890 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005891
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005893 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 }
5895
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005896 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897
5898 nsecs_t currentTime = now();
5899 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5900
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005901 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 return OK;
5903}
5904
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005905void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005906 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5907 auto& [displayId, monitors] = *it;
5908 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5909 return monitor.inputChannel->getConnectionToken() == connectionToken;
5910 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005911
Michael Wright3dd60e22019-03-27 22:06:44 +00005912 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005913 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005914 } else {
5915 ++it;
5916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 }
5918}
5919
Michael Wright3dd60e22019-03-27 22:06:44 +00005920status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005921 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005922 return pilferPointersLocked(token);
5923}
Michael Wright3dd60e22019-03-27 22:06:44 +00005924
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005925status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005926 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5927 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005928 LOG(WARNING)
5929 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005930 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005931 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005932
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005933 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005934 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005935 LOG(WARNING)
5936 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5937 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005938 return BAD_VALUE;
5939 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005940 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005941 if (deviceIds.empty()) {
5942 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005943 return BAD_VALUE;
5944 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005945
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005946 for (const DeviceId deviceId : deviceIds) {
5947 TouchState& state = *statePtr;
5948 TouchedWindow& window = *windowPtr;
5949 // Send cancel events to all the input channels we're stealing from.
5950 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5951 "input channel stole pointer stream");
5952 options.deviceId = deviceId;
5953 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005954 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
5955 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005956 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005957
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005958 std::string canceledWindows;
5959 for (const TouchedWindow& w : state.windows) {
5960 const std::shared_ptr<InputChannel> channel =
5961 getInputChannelLocked(w.windowHandle->getToken());
5962 if (channel != nullptr && channel->getConnectionToken() != token) {
5963 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5964 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5965 canceledWindows += channel->getName();
5966 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005968 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5969 LOG(INFO) << "Channel " << requestingChannel->getName()
5970 << " is stealing input gesture for device " << deviceId << " from "
5971 << canceledWindows;
5972
5973 // Prevent the gesture from being sent to any other windows.
5974 // This only blocks relevant pointers to be sent to other windows
5975 window.addPilferingPointers(deviceId, pointerIds);
5976
5977 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005978 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005979 return OK;
5980}
5981
Prabir Pradhan99987712020-11-10 18:43:05 -08005982void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5983 { // acquire lock
5984 std::scoped_lock _l(mLock);
5985 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005986 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005987 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5988 windowHandle != nullptr ? windowHandle->getName().c_str()
5989 : "token without window");
5990 }
5991
Vishnu Nairc519ff72021-01-21 08:23:08 -08005992 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005993 if (focusedToken != windowToken) {
5994 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5995 enabled ? "enable" : "disable");
5996 return;
5997 }
5998
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005999 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006000 ALOGW("Ignoring request to %s Pointer Capture: "
6001 "window has %s requested pointer capture.",
6002 enabled ? "enable" : "disable", enabled ? "already" : "not");
6003 return;
6004 }
6005
Christine Franksb768bb42021-11-29 12:11:31 -08006006 if (enabled) {
6007 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6008 mIneligibleDisplaysForPointerCapture.end(),
6009 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6010 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6011 return;
6012 }
6013 }
6014
Prabir Pradhan99987712020-11-10 18:43:05 -08006015 setPointerCaptureLocked(enabled);
6016 } // release lock
6017
6018 // Wake the thread to process command entries.
6019 mLooper->wake();
6020}
6021
Christine Franksb768bb42021-11-29 12:11:31 -08006022void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6023 { // acquire lock
6024 std::scoped_lock _l(mLock);
6025 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6026 if (!isEligible) {
6027 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6028 }
6029 } // release lock
6030}
6031
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006032std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006033 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006034 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006035 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006036 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006037 }
6038 }
6039 }
6040 return std::nullopt;
6041}
6042
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006043std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6044 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006045 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006046 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006047 }
6048
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006049 for (const auto& [token, connection] : mConnectionsByToken) {
6050 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006051 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 }
6053 }
Robert Carr4e670e52018-08-15 13:26:12 -07006054
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006055 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056}
6057
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006058std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006059 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006060 if (connection == nullptr) {
6061 return "<nullptr>";
6062 }
6063 return connection->getInputChannelName();
6064}
6065
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006066void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006067 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006068 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006069}
6070
Prabir Pradhancef936d2021-07-21 16:17:52 +00006071void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006072 const std::shared_ptr<Connection>& connection,
6073 uint32_t seq, bool handled,
6074 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006075 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006076 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006077
6078 { // Start critical section
6079 auto dispatchEntryIt =
6080 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6081 [seq](auto& e) { return e->seq == seq; });
6082 if (dispatchEntryIt == connection->waitQueue.end()) {
6083 return;
6084 }
6085
6086 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6087
6088 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6089 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6090 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6091 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6092 }
6093 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6094 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6095 connection->inputChannel->getConnectionToken(),
6096 dispatchEntry.deliveryTime, consumeTime, finishTime);
6097 }
6098
6099 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006100 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6101 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006102 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006103 }
6104 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006105
6106 // Dequeue the event and start the next cycle.
6107 // Because the lock might have been released, it is possible that the
6108 // contents of the wait queue to have been drained, so we need to double-check
6109 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006110 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6111 [seq](auto& e) { return e->seq == seq; });
6112 if (entryIt != connection->waitQueue.end()) {
6113 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6114 connection->waitQueue.erase(entryIt);
6115
Prabir Pradhancef936d2021-07-21 16:17:52 +00006116 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6117 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6118 if (!connection->responsive) {
6119 connection->responsive = isConnectionResponsive(*connection);
6120 if (connection->responsive) {
6121 // The connection was unresponsive, and now it's responsive.
6122 processConnectionResponsiveLocked(*connection);
6123 }
6124 }
6125 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006126 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6127 const InputTarget target{.inputChannel = connection->inputChannel,
6128 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006129 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006130 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006131 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006132 }
6133
6134 // Start the next dispatch cycle for this connection.
6135 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136}
6137
Prabir Pradhancef936d2021-07-21 16:17:52 +00006138void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6139 const sp<IBinder>& newToken) {
6140 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6141 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006142 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006143 };
6144 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145}
6146
Prabir Pradhancef936d2021-07-21 16:17:52 +00006147void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6148 auto command = [this, token, x, y]() REQUIRES(mLock) {
6149 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006150 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006151 };
6152 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006153}
6154
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006155void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006156 if (connection == nullptr) {
6157 LOG_ALWAYS_FATAL("Caller must check for nullness");
6158 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006159 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6160 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006161 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006162 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006163 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006164 return;
6165 }
6166 /**
6167 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6168 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6169 * has changed. This could cause newer entries to time out before the already dispatched
6170 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6171 * processes the events linearly. So providing information about the oldest entry seems to be
6172 * most useful.
6173 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006174 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6175 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006176 std::string reason =
6177 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006178 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006179 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006180 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006181 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006182 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006183
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006184 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6185
6186 // Stop waking up for events on this connection, it is already unresponsive
6187 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006188}
6189
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006190void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6191 std::string reason =
6192 StringPrintf("%s does not have a focused window", application->getName().c_str());
6193 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006194
Yabin Cui8eb9c552023-06-08 18:05:07 +00006195 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006196 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006197 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006198 };
6199 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006200}
6201
chaviw98318de2021-05-19 16:45:23 -05006202void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203 const std::string& reason) {
6204 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6205 updateLastAnrStateLocked(windowLabel, reason);
6206}
6207
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006208void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6209 const std::string& reason) {
6210 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006211 updateLastAnrStateLocked(windowLabel, reason);
6212}
6213
6214void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6215 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006217 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 struct tm tm;
6219 localtime_r(&t, &tm);
6220 char timestr[64];
6221 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006222 mLastAnrState.clear();
6223 mLastAnrState += INDENT "ANR:\n";
6224 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006225 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6226 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006227 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228}
6229
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006231 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006232 const KeyEvent event = createKeyEvent(entry);
6233 nsecs_t delay = 0;
6234 { // release lock
6235 scoped_unlock unlock(mLock);
6236 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006237 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006238 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6239 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6240 std::to_string(t.duration().count()).c_str());
6241 }
6242 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243
6244 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006245 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006246 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006247 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006249 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006250 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252}
6253
Prabir Pradhancef936d2021-07-21 16:17:52 +00006254void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006255 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006256 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006257 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006259 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006260 };
6261 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006262}
6263
Prabir Pradhanedd96402022-02-15 01:46:16 -08006264void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006265 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006266 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006267 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006268 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006269 };
6270 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006271}
6272
6273/**
6274 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6275 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6276 * command entry to the command queue.
6277 */
6278void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6279 std::string reason) {
6280 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006281 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006282 if (connection.monitor) {
6283 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6284 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006285 pid = findMonitorPidByTokenLocked(connectionToken);
6286 } else {
6287 // The connection is a window
6288 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6289 reason.c_str());
6290 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6291 if (handle != nullptr) {
6292 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006293 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006294 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006295 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006296}
6297
6298/**
6299 * Tell the policy that a connection has become responsive so that it can stop ANR.
6300 */
6301void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6302 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006303 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006304 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006305 pid = findMonitorPidByTokenLocked(connectionToken);
6306 } else {
6307 // The connection is a window
6308 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6309 if (handle != nullptr) {
6310 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006311 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006312 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006313 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006314}
6315
Prabir Pradhan24047542023-11-02 17:14:59 +00006316std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006317 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006318 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006319 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006320 if (!handled) {
6321 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006322 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006323 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006324 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006327 // Get the fallback key state.
6328 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006329 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006330 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006331 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006332 connection->inputState.removeFallbackKey(originalKeyCode);
6333 }
6334
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006335 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006336 // If the application handles the original key for which we previously
6337 // generated a fallback or if the window is not a foreground window,
6338 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006339 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006340 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006341 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6342 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6343 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6344 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6345 keyEntry.policyFlags);
6346 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006347 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006348 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349
6350 mLock.unlock();
6351
Prabir Pradhana41d2442023-04-20 21:30:40 +00006352 if (const auto unhandledKeyFallback =
6353 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6354 event, keyEntry.policyFlags);
6355 unhandledKeyFallback) {
6356 event = *unhandledKeyFallback;
6357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358
6359 mLock.lock();
6360
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006361 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006362 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006363 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006364 "application handled the original non-fallback key "
6365 "or is no longer a foreground target, "
6366 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006367 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006369 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006370 connection->inputState.removeFallbackKey(originalKeyCode);
6371 }
6372 } else {
6373 // If the application did not handle a non-fallback key, first check
6374 // that we are in a good state to perform unhandled key event processing
6375 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006376 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006377 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006378 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6379 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6380 "since this is not an initial down. "
6381 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6382 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6383 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006384 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006387 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006388 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6389 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6390 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6391 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6392 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006393 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006394
6395 mLock.unlock();
6396
Prabir Pradhana41d2442023-04-20 21:30:40 +00006397 bool fallback = false;
6398 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6399 event, keyEntry.policyFlags);
6400 fb) {
6401 fallback = true;
6402 event = *fb;
6403 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404
6405 mLock.lock();
6406
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006407 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006409 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006410 }
6411
6412 // Latch the fallback keycode for this key on an initial down.
6413 // The fallback keycode cannot change at any other point in the lifecycle.
6414 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006416 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006418 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006420 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006421 }
6422
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006423 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006424
6425 // Cancel the fallback key if the policy decides not to send it anymore.
6426 // We will continue to dispatch the key to the policy but we will no
6427 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006428 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6429 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006430 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6431 if (fallback) {
6432 ALOGD("Unhandled key event: Policy requested to send key %d"
6433 "as a fallback for %d, but on the DOWN it had requested "
6434 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006435 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006436 } else {
6437 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6438 "but on the DOWN it had requested to send %d. "
6439 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006440 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006441 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006443
Michael Wrightfb04fd52022-11-24 22:31:11 +00006444 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006445 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006446 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006447 synthesizeCancelationEventsForConnectionLocked(connection, options);
6448
6449 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006450 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006451 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006452 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453 }
6454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006455
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006456 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6457 {
6458 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006459 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006460 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 for (const auto& [key, value] : fallbackKeys) {
6462 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006463 }
6464 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6465 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006466 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006467 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468
6469 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006470 // Return the fallback key that we want dispatched to the channel.
6471 std::unique_ptr<KeyEntry> newEntry =
6472 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6473 event.getEventTime(), event.getDeviceId(),
6474 event.getSource(), event.getDisplayId(),
6475 keyEntry.policyFlags, keyEntry.action,
6476 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6477 *fallbackKeyCode, event.getScanCode(),
6478 event.getMetaState(), event.getRepeatCount(),
6479 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006480 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6481 ALOGD("Unhandled key event: Dispatching fallback key. "
6482 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006483 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006484 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006485 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006487 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6488 ALOGD("Unhandled key event: No fallback key.");
6489 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006490
6491 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006492 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493 }
6494 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006495 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006496}
6497
Michael Wrightd02c5b62014-02-10 15:10:22 -08006498void InputDispatcher::traceInboundQueueLengthLocked() {
6499 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006500 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 }
6502}
6503
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006504void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 if (ATRACE_ENABLED()) {
6506 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006507 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6508 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006509 }
6510}
6511
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006512void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513 if (ATRACE_ENABLED()) {
6514 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006515 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6516 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517 }
6518}
6519
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006520void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006521 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006523 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524 dumpDispatchStateLocked(dump);
6525
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006526 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006527 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006528 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 }
6530}
6531
6532void InputDispatcher::monitor() {
6533 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006534 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006536 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537}
6538
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006539/**
6540 * Wake up the dispatcher and wait until it processes all events and commands.
6541 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6542 * this method can be safely called from any thread, as long as you've ensured that
6543 * the work you are interested in completing has already been queued.
6544 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006545bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006546 /**
6547 * Timeout should represent the longest possible time that a device might spend processing
6548 * events and commands.
6549 */
6550 constexpr std::chrono::duration TIMEOUT = 100ms;
6551 std::unique_lock lock(mLock);
6552 mLooper->wake();
6553 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6554 return result == std::cv_status::no_timeout;
6555}
6556
Vishnu Naire798b472020-07-23 13:52:21 -07006557/**
6558 * Sets focus to the window identified by the token. This must be called
6559 * after updating any input window handles.
6560 *
6561 * Params:
6562 * request.token - input channel token used to identify the window that should gain focus.
6563 * request.focusedToken - the token that the caller expects currently to be focused. If the
6564 * specified token does not match the currently focused window, this request will be dropped.
6565 * If the specified focused token matches the currently focused window, the call will succeed.
6566 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6567 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6568 * when requesting the focus change. This determines which request gets
6569 * precedence if there is a focus change request from another source such as pointer down.
6570 */
Vishnu Nair958da932020-08-21 17:12:37 -07006571void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6572 { // acquire lock
6573 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006574 std::optional<FocusResolver::FocusChanges> changes =
6575 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6576 if (changes) {
6577 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006578 }
6579 } // release lock
6580 // Wake up poll loop since it may need to make new input dispatching choices.
6581 mLooper->wake();
6582}
6583
Vishnu Nairc519ff72021-01-21 08:23:08 -08006584void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6585 if (changes.oldFocus) {
6586 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006587 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006588 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006589 "focus left window");
6590 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006591 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006592 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006593 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006594 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006595 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006596 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006597 }
6598
Prabir Pradhan99987712020-11-10 18:43:05 -08006599 // If a window has pointer capture, then it must have focus. We need to ensure that this
6600 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6601 // If the window loses focus before it loses pointer capture, then the window can be in a state
6602 // where it has pointer capture but not focus, violating the contract. Therefore we must
6603 // dispatch the pointer capture event before the focus event. Since focus events are added to
6604 // the front of the queue (above), we add the pointer capture event to the front of the queue
6605 // after the focus events are added. This ensures the pointer capture event ends up at the
6606 // front.
6607 disablePointerCaptureForcedLocked();
6608
Vishnu Nairc519ff72021-01-21 08:23:08 -08006609 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006610 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006611 }
6612}
Vishnu Nair958da932020-08-21 17:12:37 -07006613
Prabir Pradhan99987712020-11-10 18:43:05 -08006614void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006615 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006616 return;
6617 }
6618
6619 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6620
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006621 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006622 setPointerCaptureLocked(false);
6623 }
6624
6625 if (!mWindowTokenWithPointerCapture) {
6626 // No need to send capture changes because no window has capture.
6627 return;
6628 }
6629
6630 if (mPendingEvent != nullptr) {
6631 // Move the pending event to the front of the queue. This will give the chance
6632 // for the pending event to be dropped if it is a captured event.
6633 mInboundQueue.push_front(mPendingEvent);
6634 mPendingEvent = nullptr;
6635 }
6636
6637 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006638 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006639 mInboundQueue.push_front(std::move(entry));
6640}
6641
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006642void InputDispatcher::setPointerCaptureLocked(bool enable) {
6643 mCurrentPointerCaptureRequest.enable = enable;
6644 mCurrentPointerCaptureRequest.seq++;
6645 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006646 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006647 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006648 };
6649 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006650}
6651
Vishnu Nair599f1412021-06-21 10:39:58 -07006652void InputDispatcher::displayRemoved(int32_t displayId) {
6653 { // acquire lock
6654 std::scoped_lock _l(mLock);
6655 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006656 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006657 setFocusedApplicationLocked(displayId, nullptr);
6658 // Call focus resolver to clean up stale requests. This must be called after input windows
6659 // have been removed for the removed display.
6660 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006661 // Reset pointer capture eligibility, regardless of previous state.
6662 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006663 // Remove the associated touch mode state.
6664 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006665 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006666 } // release lock
6667
6668 // Wake up poll loop since it may need to make new input dispatching choices.
6669 mLooper->wake();
6670}
6671
Patrick Williamsd828f302023-04-28 17:52:08 -05006672void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006673 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6674 {
6675 // acquire lock
6676 std::scoped_lock _l(mLock);
6677 logDispatchStateLocked();
6678 }
6679 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6680 result.error().message().c_str());
6681 };
chaviw15fab6f2021-06-07 14:15:52 -05006682 // The listener sends the windows as a flattened array. Separate the windows by display for
6683 // more convenient parsing.
6684 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006685 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006686 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006687 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006688 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006689
6690 { // acquire lock
6691 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006692
6693 // Ensure that we have an entry created for all existing displays so that if a displayId has
6694 // no windows, we can tell that the windows were removed from the display.
6695 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6696 handlesPerDisplay[displayId];
6697 }
6698
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006699 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006700 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006701 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6702 }
6703
6704 for (const auto& [displayId, handles] : handlesPerDisplay) {
6705 setInputWindowsLocked(handles, displayId);
6706 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006707
6708 if (update.vsyncId < mWindowInfosVsyncId) {
6709 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6710 ", current update vsync id: %" PRId64,
6711 mWindowInfosVsyncId, update.vsyncId);
6712 }
6713 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006714 }
6715 // Wake up poll loop since it may need to make new input dispatching choices.
6716 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006717}
6718
Vishnu Nair062a8672021-09-03 16:07:44 -07006719bool InputDispatcher::shouldDropInput(
6720 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006721 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6722 (windowHandle->getInfo()->inputConfig.test(
6723 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006724 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006725 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6726 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006727 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006728 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006729 windowHandle->getInfo()->displayId);
6730 return true;
6731 }
6732 return false;
6733}
6734
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006735void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006736 const gui::WindowInfosUpdate& update) {
6737 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006738}
6739
Arthur Hungdfd528e2021-12-08 13:23:04 +00006740void InputDispatcher::cancelCurrentTouch() {
6741 {
6742 std::scoped_lock _l(mLock);
6743 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006744 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006745 "cancel current touch");
6746 synthesizeCancelationEventsForAllConnectionsLocked(options);
6747
6748 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006749 }
6750 // Wake up poll loop since there might be work to do.
6751 mLooper->wake();
6752}
6753
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006754void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6755 std::scoped_lock _l(mLock);
6756 mMonitorDispatchingTimeout = timeout;
6757}
6758
Arthur Hungc539dbb2022-12-08 07:45:36 +00006759void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6760 const sp<WindowInfoHandle>& oldWindowHandle,
6761 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006762 TouchState& state, int32_t deviceId,
6763 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006764 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006765 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006766 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6767 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6768 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6769 newWindowHandle->getInfo()->inputConfig.test(
6770 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6771 const sp<WindowInfoHandle> oldWallpaper =
6772 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6773 const sp<WindowInfoHandle> newWallpaper =
6774 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6775 if (oldWallpaper == newWallpaper) {
6776 return;
6777 }
6778
6779 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006780 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006781 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006782 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006783 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006784 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006785 }
6786
6787 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006788 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6789 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006790 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006791 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006792 }
6793}
6794
6795void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6796 ftl::Flags<InputTarget::Flags> newTargetFlags,
6797 const sp<WindowInfoHandle> fromWindowHandle,
6798 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006799 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006800 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006801 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6802 fromWindowHandle->getInfo()->inputConfig.test(
6803 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6804 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6805 toWindowHandle->getInfo()->inputConfig.test(
6806 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6807
6808 const sp<WindowInfoHandle> oldWallpaper =
6809 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6810 const sp<WindowInfoHandle> newWallpaper =
6811 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6812 if (oldWallpaper == newWallpaper) {
6813 return;
6814 }
6815
6816 if (oldWallpaper != nullptr) {
6817 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6818 "transferring touch focus to another window");
6819 state.removeWindowByToken(oldWallpaper->getToken());
6820 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6821 }
6822
6823 if (newWallpaper != nullptr) {
6824 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006825 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006826 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6827 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006828 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006829 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006830 std::shared_ptr<Connection> wallpaperConnection =
6831 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006832 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006833 std::shared_ptr<Connection> toConnection =
6834 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006835 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6836 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6837 wallpaperFlags);
6838 }
6839 }
6840}
6841
6842sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6843 const sp<WindowInfoHandle>& windowHandle) const {
6844 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6845 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6846 bool foundWindow = false;
6847 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6848 if (!foundWindow && otherHandle != windowHandle) {
6849 continue;
6850 }
6851 if (windowHandle == otherHandle) {
6852 foundWindow = true;
6853 continue;
6854 }
6855
6856 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6857 return otherHandle;
6858 }
6859 }
6860 return nullptr;
6861}
6862
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006863void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6864 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006865 std::scoped_lock _l(mLock);
6866
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006867 mConfig.keyRepeatTimeout = timeout.count();
6868 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006869}
6870
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006871bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6872 DeviceId deviceId, int32_t pointerId) {
6873 std::scoped_lock _l(mLock);
6874 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6875 if (touchStateIt == mTouchStatesByDisplay.end()) {
6876 return false;
6877 }
6878 for (const TouchedWindow& window : touchStateIt->second.windows) {
6879 if (window.windowHandle->getToken() == token &&
6880 (window.hasTouchingPointer(deviceId, pointerId) ||
6881 window.hasHoveringPointer(deviceId, pointerId))) {
6882 return true;
6883 }
6884 }
6885 return false;
6886}
6887
Garfield Tane84e6f92019-08-29 17:28:41 -07006888} // namespace android::inputdispatcher