blob: 0ddea7195af42f87f63bbec1fda26e52d1550cc1 [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
Siarhei Vishniakou18a1d512023-12-15 13:47:33 -080075// TODO(b/312714754): remove the corresponding code, as well.
76static const bool REMOVE_APP_SWITCH_DROPS = true;
Siarhei Vishniakou17f12282023-11-02 13:40:29 -070077
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
Prabir Pradhancef936d2021-07-21 16:17:52 +000080namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000081
82template <class Entry>
83void ensureEventTraced(const Entry& entry) {
84 if (!entry.traceTracker) {
85 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
86 }
87}
88
Prabir Pradhancef936d2021-07-21 16:17:52 +000089// Temporarily releases a held mutex for the lifetime of the instance.
90// Named to match std::scoped_lock
91class scoped_unlock {
92public:
93 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
94 ~scoped_unlock() { mMutex.lock(); }
95
96private:
97 std::mutex& mMutex;
98};
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100// Default input dispatching timeout if there is no focused application or paused window
101// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800102const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
103 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
104 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105
106// Amount of time to allow for all pending events to be processed when an app switch
107// key is on the way. This is used to preempt input dispatch and drop input events
108// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800111const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113// 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 +0000114constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
115
116// Log a warning when an interception call takes longer than this to process.
117constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700119// Additional key latency in case a connection is still processing some motion events.
120// This will help with the case when a user touched a button that opens a new window,
121// and gives us the chance to dispatch the key to this new window.
122constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
123
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000125constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
126
Antonio Kantekea47acb2021-12-23 12:41:25 -0800127// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000128constexpr int LOGTAG_INPUT_INTERACTION = 62000;
129constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000130constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000131
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000132const ui::Transform kIdentityTransform;
133
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000134inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 return systemTime(SYSTEM_TIME_MONOTONIC);
136}
137
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700138inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000139 if (binder == nullptr) {
140 return "<null>";
141 }
142 return StringPrintf("%p", binder.get());
143}
144
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000145static std::string uidString(const gui::Uid& uid) {
146 return uid.toString();
147}
148
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700149Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700151 case AKEY_EVENT_ACTION_DOWN:
152 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700153 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 }
157}
158
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159Result<void> validateKeyEvent(int32_t action) {
160 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161}
162
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800164 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700166 case AMOTION_EVENT_ACTION_UP: {
167 if (pointerCount != 1) {
168 return Error() << "invalid pointer count " << pointerCount;
169 }
170 return {};
171 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_HOVER_ENTER:
174 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700175 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
176 if (pointerCount < 1) {
177 return Error() << "invalid pointer count " << pointerCount;
178 }
179 return {};
180 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800181 case AMOTION_EVENT_ACTION_CANCEL:
182 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700184 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 case AMOTION_EVENT_ACTION_POINTER_DOWN:
186 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800187 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700188 if (index < 0) {
189 return Error() << "invalid index " << index << " for "
190 << MotionEvent::actionToString(action);
191 }
192 if (index >= pointerCount) {
193 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
194 }
195 if (pointerCount <= 1) {
196 return Error() << "invalid pointer count " << pointerCount << " for "
197 << MotionEvent::actionToString(action);
198 }
199 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 }
201 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700202 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
203 if (actionButton == 0) {
204 return Error() << "action button should be nonzero for "
205 << MotionEvent::actionToString(action);
206 }
207 return {};
208 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700209 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700210 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212}
213
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000214int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500215 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
216}
217
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
219 const PointerProperties* pointerProperties) {
220 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
221 if (!actionCheck.ok()) {
222 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
224 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer count " << pointerCount
226 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 for (size_t i = 0; i < pointerCount; i++) {
230 int32_t id = pointerProperties[i].id;
231 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 return Error() << "Motion event has invalid pointer id " << id
233 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800235 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700236 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800238 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return {};
241}
242
243Result<void> validateInputEvent(const InputEvent& event) {
244 switch (event.getType()) {
245 case InputEventType::KEY: {
246 const KeyEvent& key = static_cast<const KeyEvent&>(event);
247 const int32_t action = key.getAction();
248 return validateKeyEvent(action);
249 }
250 case InputEventType::MOTION: {
251 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
252 const int32_t action = motion.getAction();
253 const size_t pointerCount = motion.getPointerCount();
254 const PointerProperties* pointerProperties = motion.getPointerProperties();
255 const int32_t actionButton = motion.getActionButton();
256 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
257 }
258 default: {
259 return {};
260 }
261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262}
263
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800264std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
265 std::bitset<MAX_POINTER_ID + 1> pointerIds;
266 for (const PointerProperties& pointer : pointers) {
267 pointerIds.set(pointer.id);
268 }
269 return pointerIds;
270}
271
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000272std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000274 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275 }
276
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000277 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 bool first = true;
279 Region::const_iterator cur = region.begin();
280 Region::const_iterator const tail = region.end();
281 while (cur != tail) {
282 if (first) {
283 first = false;
284 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800285 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800287 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 cur++;
289 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000290 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291}
292
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000293std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
294 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500295 constexpr size_t maxEntries = 50; // max events to print
296 constexpr size_t skipBegin = maxEntries / 2;
297 const size_t skipEnd = queue.size() - maxEntries / 2;
298 // skip from maxEntries / 2 ... size() - maxEntries/2
299 // only print from 0 .. skipBegin and then from skipEnd .. size()
300
301 std::string dump;
302 for (size_t i = 0; i < queue.size(); i++) {
303 const DispatchEntry& entry = *queue[i];
304 if (i >= skipBegin && i < skipEnd) {
305 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
306 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
307 continue;
308 }
309 dump.append(INDENT4);
310 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000311 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
312 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500313 ns2ms(currentTime - entry.eventEntry->eventTime));
314 if (entry.deliveryTime != 0) {
315 // This entry was delivered, so add information on how long we've been waiting
316 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
317 }
318 dump.append("\n");
319 }
320 return dump;
321}
322
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700323/**
324 * Find the entry in std::unordered_map by key, and return it.
325 * If the entry is not found, return a default constructed entry.
326 *
327 * Useful when the entries are vectors, since an empty vector will be returned
328 * if the entry is not found.
329 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
330 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700331template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000332V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700333 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700334 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800335}
336
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700338 if (first == second) {
339 return true;
340 }
341
342 if (first == nullptr || second == nullptr) {
343 return false;
344 }
345
346 return first->getToken() == second->getToken();
347}
348
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000349bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000350 if (first == nullptr || second == nullptr) {
351 return false;
352 }
353 return first->applicationInfo.token != nullptr &&
354 first->applicationInfo.token == second->applicationInfo.token;
355}
356
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800357template <typename T>
358size_t firstMarkedBit(T set) {
359 // TODO: replace with std::countr_zero from <bit> when that's available
360 LOG_ALWAYS_FATAL_IF(set.none());
361 size_t i = 0;
362 while (!set.test(i)) {
363 i++;
364 }
365 return i;
366}
367
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800368std::unique_ptr<DispatchEntry> createDispatchEntry(
Prabir Pradhan24047542023-11-02 17:14:59 +0000369 const InputTarget& inputTarget, std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800370 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700371 if (inputTarget.useDefaultPointerTransform()) {
372 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700373 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700374 inputTarget.displayTransform,
375 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376 }
377
378 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
379 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
380
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700381 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700382 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000383
384 // Use the first pointer information to normalize all other pointers. This could be any pointer
385 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700386 // uses the transform for the normalized pointer.
387 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800388 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700389 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390
391 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700392 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000393 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
394 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700395 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000396
397 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700398 // First, apply the current pointer's transform to update the coordinates into
399 // window space.
400 pointerCoords[pointerIndex].transform(currTransform);
401 // Next, apply the inverse transform of the normalized coordinates so the
402 // current coordinates are transformed into the normalized coordinate space.
403 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404 }
405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700406 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000407 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
408 motionEntry.eventTime, motionEntry.deviceId,
409 motionEntry.source, motionEntry.displayId,
410 motionEntry.policyFlags, motionEntry.action,
411 motionEntry.actionButton, motionEntry.flags,
412 motionEntry.metaState, motionEntry.buttonState,
413 motionEntry.classification, motionEntry.edgeFlags,
414 motionEntry.xPrecision, motionEntry.yPrecision,
415 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
416 motionEntry.downTime, motionEntry.pointerProperties,
417 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000418
419 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700420 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700421 firstPointerTransform, inputTarget.displayTransform,
422 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000423 return dispatchEntry;
424}
425
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000426status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
427 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700428 std::unique_ptr<InputChannel> uniqueServerChannel;
429 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
430
431 serverChannel = std::move(uniqueServerChannel);
432 return result;
433}
434
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500435template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500437 if (lhs == nullptr && rhs == nullptr) {
438 return true;
439 }
440 if (lhs == nullptr || rhs == nullptr) {
441 return false;
442 }
443 return *lhs == *rhs;
444}
445
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000446KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000447 KeyEvent event;
448 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
449 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
450 entry.repeatCount, entry.downTime, entry.eventTime);
451 return event;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000455 // Do not keep track of gesture monitors. They receive every event and would disproportionately
456 // affect the statistics.
457 if (connection.monitor) {
458 return false;
459 }
460 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
461 if (!connection.responsive) {
462 return false;
463 }
464 return true;
465}
466
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000467bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000468 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
469 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000470 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
471 return false;
472 }
473 // Only track latency for events that originated from hardware
474 if (eventEntry.isSynthesized()) {
475 return false;
476 }
477 const EventEntry::Type& inputEventEntryType = eventEntry.type;
478 if (inputEventEntryType == EventEntry::Type::KEY) {
479 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
480 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
481 return false;
482 }
483 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
484 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
485 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
486 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
487 return false;
488 }
489 } else {
490 // Not a key or a motion
491 return false;
492 }
493 if (!shouldReportMetricsForConnection(connection)) {
494 return false;
495 }
496 return true;
497}
498
Prabir Pradhancef936d2021-07-21 16:17:52 +0000499/**
500 * Connection is responsive if it has no events in the waitQueue that are older than the
501 * current time.
502 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000503bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000504 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000505 for (const auto& dispatchEntry : connection.waitQueue) {
506 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000507 return false;
508 }
509 }
510 return true;
511}
512
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513// Returns true if the event type passed as argument represents a user activity.
514bool isUserActivityEvent(const EventEntry& eventEntry) {
515 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::CONFIGURATION_CHANGED:
517 case EventEntry::Type::DEVICE_RESET:
518 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000519 case EventEntry::Type::FOCUS:
520 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000521 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000522 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000523 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000524 case EventEntry::Type::KEY:
525 case EventEntry::Type::MOTION:
526 return true;
527 }
528}
529
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000531bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000532 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 const auto inputConfig = windowInfo.inputConfig;
534 if (windowInfo.displayId != displayId ||
535 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800536 return false;
537 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700538 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800539 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800540 return false;
541 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000542
543 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
544 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
545 // the window. Points on the right and bottom edges should not be inside the window, so we need
546 // to be careful about performing a hit test when the display is rotated, since the "right" and
547 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
548 // logical display in which WM determined the bounds. Perform the hit test in the logical
549 // display space to ensure these edges are considered correctly in all orientations.
550 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
551 const auto p = displayTransform.transform(x, y);
552 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800553 return false;
554 }
555 return true;
556}
557
Prabir Pradhand65552b2021-10-07 11:23:50 -0700558bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
559 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000560 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700561}
562
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800563// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000564// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
565// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
566// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800567// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000568bool canReceiveForegroundTouches(const WindowInfo& info) {
569 // A non-touchable window can still receive touch events (e.g. in the case of
570 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
571 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
572}
573
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000574bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700575 if (windowHandle == nullptr) {
576 return false;
577 }
578 const WindowInfo* windowInfo = windowHandle->getInfo();
579 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
580 return true;
581 }
582 return false;
583}
584
Prabir Pradhan5735a322022-04-11 17:23:34 +0000585// Checks targeted injection using the window's owner's uid.
586// Returns an empty string if an entry can be sent to the given window, or an error message if the
587// entry is a targeted injection whose uid target doesn't match the window owner.
588std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
589 const EventEntry& entry) {
590 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
591 // The event was not injected, or the injected event does not target a window.
592 return {};
593 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000595 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000596 return StringPrintf("No valid window target for injection into uid %s.",
597 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000600 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
601 "owned by uid %s.",
602 uid.toString().c_str(), window->getName().c_str(),
603 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000604 }
605 return {};
606}
607
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000608std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700609 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
610 // Always dispatch mouse events to cursor position.
611 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000612 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700613 }
614
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700615 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000616 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
617 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700618}
619
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700620std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
621 if (eventEntry.type == EventEntry::Type::KEY) {
622 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
623 return keyEntry.downTime;
624 } else if (eventEntry.type == EventEntry::Type::MOTION) {
625 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
626 return motionEntry.downTime;
627 }
628 return std::nullopt;
629}
630
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000631/**
632 * Compare the old touch state to the new touch state, and generate the corresponding touched
633 * windows (== input targets).
634 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
635 * If the pointer just entered the new window, produce HOVER_ENTER.
636 * For pointers remaining in the window, produce HOVER_MOVE.
637 */
638std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
639 const TouchState& newTouchState,
640 const MotionEntry& entry) {
641 std::vector<TouchedWindow> out;
642 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700643
644 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
645 // ACTION_SCROLL events should not affect the hovering pointer dispatch
646 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000647 }
648
649 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800650 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000651
652 std::set<sp<WindowInfoHandle>> oldWindows;
653 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800654 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000655 }
656
657 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800658 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000659
660 // If the pointer is no longer in the new window set, send HOVER_EXIT.
661 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
662 if (newWindows.find(oldWindow) == newWindows.end()) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000665 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000666 out.push_back(touchedWindow);
667 }
668 }
669
670 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
671 TouchedWindow touchedWindow;
672 touchedWindow.windowHandle = newWindow;
673 if (oldWindows.find(newWindow) == oldWindows.end()) {
674 // Any windows that have this pointer now, and didn't have it before, should get
675 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000676 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 } else {
678 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700679 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700680 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000681 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
682 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700683 // The Accessibility injected touch exploration event stream
684 // has known inconsistencies, so log ERROR instead of
685 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700686 severity = android::base::LogSeverity::ERROR;
687 }
688 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700689 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000690 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000691 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800692 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000693 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
694 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
695 }
696 out.push_back(touchedWindow);
697 }
698 return out;
699}
700
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800701template <typename T>
702std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
703 left.insert(left.end(), right.begin(), right.end());
704 return left;
705}
706
Harry Cuttsb166c002023-05-09 13:06:05 +0000707// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
708// both.
709void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
710 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
711 if (!window.windowHandle->getInfo()->inputConfig.test(
712 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
713 // In addition to TouchState, erase this window from the input targets! We don't have a
714 // good way to do this today except by adding a nested loop.
715 // TODO(b/282025641): simplify this code once InputTargets are being identified
716 // separately from TouchedWindows.
717 std::erase_if(targets, [&](const InputTarget& target) {
718 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
719 });
720 return true;
721 }
722 return false;
723 });
724}
725
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700726/**
727 * In general, touch should be always split between windows. Some exceptions:
728 * 1. Don't split touch if all of the below is true:
729 * (a) we have an active pointer down *and*
730 * (b) a new pointer is going down that's from the same device *and*
731 * (c) the window that's receiving the current pointer does not support split touch.
732 * 2. Don't split mouse events
733 */
734bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
735 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
736 // We should never split mouse events
737 return false;
738 }
739 for (const TouchedWindow& touchedWindow : touchState.windows) {
740 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
741 // Spy windows should not affect whether or not touch is split.
742 continue;
743 }
744 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
745 continue;
746 }
747 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
748 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
749 // Wallpaper window should not affect whether or not touch is split
750 continue;
751 }
752
753 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
754 return false;
755 }
756 }
757 return true;
758}
759
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700760/**
761 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
762 */
763bool isStylusActiveInDisplay(
764 int32_t displayId,
765 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
766 const auto it = touchStatesByDisplay.find(displayId);
767 if (it == touchStatesByDisplay.end()) {
768 return false;
769 }
770 const TouchState& state = it->second;
771 return state.hasActiveStylus();
772}
773
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800774Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
775 struct HashFunction {
776 size_t operator()(const WindowInfo& info) const { return info.id; }
777 };
778
779 std::unordered_set<WindowInfo, HashFunction> windowSet;
780 for (const WindowInfo& info : update.windowInfos) {
781 const auto [_, inserted] = windowSet.insert(info);
782 if (!inserted) {
783 return Error() << "Duplicate entry for " << info;
784 }
785 }
786 return {};
787}
788
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000789} // namespace
790
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791// --- InputDispatcher ---
792
Prabir Pradhana41d2442023-04-20 21:30:40 +0000793InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000794 : InputDispatcher(policy, nullptr) {}
795
796InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
797 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700798 : mPolicy(policy),
799 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800801 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700802 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700803 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700804 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800805 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700806 mDispatchEnabled(false),
807 mDispatchFrozen(false),
808 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100809 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000810 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800811 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000812 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000813 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700814 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800815 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700817 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700818#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700819 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700820#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700821 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000822
823 if (traceBackend) {
824 // TODO: Create input tracer instance.
825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826}
827
828InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000829 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830
Prabir Pradhancef936d2021-07-21 16:17:52 +0000831 resetKeyRepeatLocked();
832 releasePendingEventLocked();
833 drainInboundQueueLocked();
834 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000836 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700837 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000838 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840}
841
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700842status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700843 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700844 return ALREADY_EXISTS;
845 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700846 mThread = std::make_unique<InputThread>(
847 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
848 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700849}
850
851status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700852 if (mThread && mThread->isCallingThread()) {
853 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700854 return INVALID_OPERATION;
855 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700856 mThread.reset();
857 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700858}
859
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700861 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800863 std::scoped_lock _l(mLock);
864 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865
866 // Run a dispatch loop if there are no pending commands.
867 // The dispatch loop might enqueue commands to run afterwards.
868 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800869 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
871
872 // Run all pending commands if there are any.
873 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000874 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700875 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800877
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700878 // If we are still waiting for ack on some events,
879 // we might have to wake up earlier to check if an app is anr'ing.
880 const nsecs_t nextAnrCheck = processAnrsLocked();
881 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
882
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800883 // We are about to enter an infinitely long sleep, because we have no commands or
884 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700885 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800886 mDispatcherEnteredIdle.notify_all();
887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 } // release lock
889
890 // Wait for callback or timeout or wake. (make sure we round up, not down)
891 nsecs_t currentTime = now();
892 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
893 mLooper->pollOnce(timeoutMillis);
894}
895
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500897 * Raise ANR if there is no focused window.
898 * Before the ANR is raised, do a final state check:
899 * 1. The currently focused application must be the same one we are waiting for.
900 * 2. Ensure we still don't have a focused window.
901 */
902void InputDispatcher::processNoFocusedWindowAnrLocked() {
903 // Check if the application that we are waiting for is still focused.
904 std::shared_ptr<InputApplicationHandle> focusedApplication =
905 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
906 if (focusedApplication == nullptr ||
907 focusedApplication->getApplicationToken() !=
908 mAwaitedFocusedApplication->getApplicationToken()) {
909 // Unexpected because we should have reset the ANR timer when focused application changed
910 ALOGE("Waited for a focused window, but focused application has already changed to %s",
911 focusedApplication->getName().c_str());
912 return; // The focused application has changed.
913 }
914
chaviw98318de2021-05-19 16:45:23 -0500915 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500916 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
917 if (focusedWindowHandle != nullptr) {
918 return; // We now have a focused window. No need for ANR.
919 }
920 onAnrLocked(mAwaitedFocusedApplication);
921}
922
923/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700924 * Check if any of the connections' wait queues have events that are too old.
925 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
926 * Return the time at which we should wake up next.
927 */
928nsecs_t InputDispatcher::processAnrsLocked() {
929 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700930 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
932 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
933 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500934 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700935 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500936 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700937 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500939 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700940 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
941 }
942 }
943
944 // Check if any connection ANRs are due
945 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
946 if (currentTime < nextAnrCheck) { // most likely scenario
947 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
948 }
949
950 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700951 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700952 if (connection == nullptr) {
953 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
954 return nextAnrCheck;
955 }
956 connection->responsive = false;
957 // Stop waking up for this unresponsive connection
958 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000959 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700960 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700961}
962
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800963std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700964 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800965 if (connection->monitor) {
966 return mMonitorDispatchingTimeout;
967 }
968 const sp<WindowInfoHandle> window =
969 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700970 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500971 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700972 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500973 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700974}
975
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800976void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 nsecs_t currentTime = now();
978
Jeff Browndc5992e2014-04-11 01:27:26 -0700979 // Reset the key repeat timer whenever normal dispatch is suspended while the
980 // device is in a non-interactive state. This is to ensure that we abort a key
981 // repeat if the device is just coming out of sleep.
982 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 resetKeyRepeatLocked();
984 }
985
986 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
987 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100988 if (DEBUG_FOCUS) {
989 ALOGD("Dispatch frozen. Waiting some more.");
990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 return;
992 }
993
994 // Optimize latency of app switches.
995 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
996 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700997 bool isAppSwitchDue;
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700998 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700999 isAppSwitchDue = mAppSwitchDueTime <= currentTime;
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001000 nextWakeupTime = std::min(nextWakeupTime, mAppSwitchDueTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 // Ready to start a new event.
1004 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001005 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001006 if (mInboundQueue.empty()) {
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001007 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001008 if (isAppSwitchDue) {
1009 // The inbound queue is empty so the app switch key we were waiting
1010 // for will never arrive. Stop waiting for it.
1011 resetPendingAppSwitchLocked(false);
1012 isAppSwitchDue = false;
1013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 // Synthesize a key repeat if appropriate.
1017 if (mKeyRepeatState.lastKeyEntry) {
1018 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1019 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1020 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001021 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
1023 }
1024
1025 // Nothing to do if there is no pending event.
1026 if (!mPendingEvent) {
1027 return;
1028 }
1029 } else {
1030 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001031 mPendingEvent = mInboundQueue.front();
1032 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 traceInboundQueueLengthLocked();
1034 }
1035
1036 // Poke user activity for this event.
1037 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
1041
1042 // Now we have an event to dispatch.
1043 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001044 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001048 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052
1053 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001054 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056
1057 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001058 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001059 const ConfigurationChangedEntry& typedEntry =
1060 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001062 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063 break;
1064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067 const DeviceResetEntry& typedEntry =
1068 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001070 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 break;
1072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001074 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001075 std::shared_ptr<const FocusEntry> typedEntry =
1076 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001077 dispatchFocusLocked(currentTime, typedEntry);
1078 done = true;
1079 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1080 break;
1081 }
1082
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001083 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001084 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001085 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1086 done = true;
1087 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1088 break;
1089 }
1090
Prabir Pradhan99987712020-11-10 18:43:05 -08001091 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1092 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001093 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001094 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1095 done = true;
1096 break;
1097 }
1098
arthurhungb89ccb02020-12-30 16:19:01 +08001099 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001100 std::shared_ptr<const DragEntry> typedEntry =
1101 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001102 dispatchDragLocked(currentTime, typedEntry);
1103 done = true;
1104 break;
1105 }
1106
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001107 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001108 std::shared_ptr<const KeyEntry> keyEntry =
1109 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001110 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001111 if (isAppSwitchDue) {
1112 if (isAppSwitchKeyEvent(*keyEntry)) {
1113 resetPendingAppSwitchLocked(true);
1114 isAppSwitchDue = false;
1115 } else if (dropReason == DropReason::NOT_DROPPED) {
1116 dropReason = DropReason::APP_SWITCH;
1117 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 }
1119 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001120 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1124 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001126 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001127 if (done && mTracer) {
1128 ensureEventTraced(*keyEntry);
1129 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1130 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 break;
1132 }
1133
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001134 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001135 std::shared_ptr<const MotionEntry> motionEntry =
1136 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001137 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001138 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1139 dropReason = DropReason::APP_SWITCH;
1140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001142 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001143 // The event is stale. However, only drop stale events if there isn't an ongoing
1144 // gesture. That would allow us to complete the processing of the current stroke.
1145 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1146 if (touchStateIt != mTouchStatesByDisplay.end()) {
1147 const TouchState& touchState = touchStateIt->second;
1148 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1149 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1150 dropReason = DropReason::STALE;
1151 }
1152 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001154 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001155 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1156 // Only drop events that are focus-dispatched.
1157 dropReason = DropReason::BLOCKED;
1158 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001161 if (done && mTracer) {
1162 ensureEventTraced(*motionEntry);
1163 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
Chris Yef59a2f42020-10-16 12:55:26 -07001167
1168 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001169 std::shared_ptr<const SensorEntry> sensorEntry =
1170 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001171 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001172 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1173 dropReason = DropReason::APP_SWITCH;
1174 }
Chris Yef59a2f42020-10-16 12:55:26 -07001175 }
1176 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1177 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1178 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1179 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1180 dropReason = DropReason::STALE;
1181 }
1182 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1183 done = true;
1184 break;
1185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 }
1187
1188 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001189 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001190 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
Michael Wright3a981722015-06-10 15:26:13 +01001192 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193
1194 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001195 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197}
1198
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001199bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001200 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001201}
1202
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001203/**
1204 * Return true if the events preceding this incoming motion event should be dropped
1205 * Return false otherwise (the default behaviour)
1206 */
1207bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001208 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001209 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001210
1211 // Optimize case where the current application is unresponsive and the user
1212 // decides to touch a window in a different application.
1213 // If the application takes too long to catch up then we drop all events preceding
1214 // the touch into the other window.
1215 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001216 const int32_t displayId = motionEntry.displayId;
1217 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001218 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001219
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001220 sp<WindowInfoHandle> touchedWindowHandle =
1221 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001222 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001223 touchedWindowHandle->getApplicationToken() !=
1224 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001225 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 ALOGI("Pruning input queue because user touched a different application while waiting "
1227 "for %s",
1228 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001229 return true;
1230 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001231
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001232 // Alternatively, maybe there's a spy window that could handle this event.
1233 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1234 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1235 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001236 const std::shared_ptr<Connection> connection =
1237 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001238 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001239 // This spy window could take more input. Drop all events preceding this
1240 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001241 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001242 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001243 mAwaitedFocusedApplication->getName().c_str());
1244 return true;
1245 }
1246 }
1247 }
1248
1249 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1250 // yet been processed by some connections, the dispatcher will wait for these motion
1251 // events to be processed before dispatching the key event. This is because these motion events
1252 // may cause a new window to be launched, which the user might expect to receive focus.
1253 // To prevent waiting forever for such events, just send the key to the currently focused window
1254 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1255 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1256 "just send the pending key event to the focused window.");
1257 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001258 }
1259 return false;
1260}
1261
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001263 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001265 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 traceInboundQueueLengthLocked();
1267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001269 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001270 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1271 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 // Optimize app switch latency.
1273 // If the application takes too long to catch up then we drop all events preceding
1274 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001276 if (mTracer) {
1277 ensureEventTraced(keyEntry);
1278 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001279
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001280 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001281 if (isAppSwitchKeyEvent(keyEntry)) {
1282 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
1283 mAppSwitchSawKeyDown = true;
1284 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
1285 if (mAppSwitchSawKeyDown) {
1286 if (DEBUG_APP_SWITCH) {
1287 ALOGD("App switch is pending!");
1288 }
1289 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
1290 mAppSwitchSawKeyDown = false;
1291 needWake = true;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001292 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 }
1294 }
1295 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001296 // If a new up event comes in, and the pending event with same key code has been asked
1297 // to try again later because of the policy. We have to reset the intercept key wake up
1298 // time for it may have been handled in the policy and could be dropped.
1299 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1300 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001301 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001302 if (pendingKey.keyCode == keyEntry.keyCode &&
1303 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001304 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1305 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001306 pendingKey.interceptKeyWakeupTime = 0;
1307 needWake = true;
1308 }
1309 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001310 break;
1311 }
1312
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001313 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001314 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1315 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001316 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1317 if (mTracer) {
1318 ensureEventTraced(motionEntry);
1319 }
1320 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001322 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001326 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001327 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1328 break;
1329 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001330 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001331 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001333 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001334 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1335 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001336 // nothing to do
1337 break;
1338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
1341 return needWake;
1342}
1343
Prabir Pradhan24047542023-11-02 17:14:59 +00001344void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001345 // Do not store sensor event in recent queue to avoid flooding the queue.
1346 if (entry->type != EventEntry::Type::SENSOR) {
1347 mRecentQueue.push_back(entry);
1348 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001349 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001350 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
1352}
1353
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001354sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1355 bool isStylus,
1356 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001358 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001359 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001360 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001361 continue;
1362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001364 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001365 if (!info.isSpy() &&
1366 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001367 return windowHandle;
1368 }
1369 }
1370 return nullptr;
1371}
1372
1373std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001374 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001375 if (touchedWindow == nullptr) {
1376 return {};
1377 }
1378 // Traverse windows from front to back until we encounter the touched window.
1379 std::vector<InputTarget> outsideTargets;
1380 const auto& windowHandles = getWindowHandlesLocked(displayId);
1381 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1382 if (windowHandle == touchedWindow) {
1383 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1384 // below the touched window will not get ACTION_OUTSIDE event.
1385 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001386 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001387
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001388 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001389 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001390 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1391 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001392 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1393 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001394 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
1396 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001397 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398}
1399
Prabir Pradhand65552b2021-10-07 11:23:50 -07001400std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001401 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001402 // Traverse windows from front to back and gather the touched spy windows.
1403 std::vector<sp<WindowInfoHandle>> spyWindows;
1404 const auto& windowHandles = getWindowHandlesLocked(displayId);
1405 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1406 const WindowInfo& info = *windowHandle->getInfo();
1407
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001408 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001409 continue;
1410 }
1411 if (!info.isSpy()) {
1412 // The first touched non-spy window was found, so return the spy windows touched so far.
1413 return spyWindows;
1414 }
1415 spyWindows.push_back(windowHandle);
1416 }
1417 return spyWindows;
1418}
1419
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001420void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 const char* reason;
1422 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001423 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001424 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001425 ALOGD("Dropped event because policy consumed it.");
1426 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 reason = "inbound event was dropped because the policy consumed it";
1428 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001429 case DropReason::DISABLED:
1430 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 ALOGI("Dropped event because input dispatch is disabled.");
1432 }
1433 reason = "inbound event was dropped because input dispatch is disabled";
1434 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001435 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001436 ALOGI("Dropped event because of pending overdue app switch.");
1437 reason = "inbound event was dropped because of pending overdue app switch";
1438 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001439 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001440 LOG(INFO) << "Dropping because the current application is not responding and the user "
1441 "has started interacting with a different application: "
1442 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 reason = "inbound event was dropped because the current application is not responding "
1444 "and the user has started interacting with a different application";
1445 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001446 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001447 ALOGI("Dropped event because it is stale.");
1448 reason = "inbound event was dropped because it is stale";
1449 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001450 case DropReason::NO_POINTER_CAPTURE:
1451 ALOGI("Dropped event because there is no window with Pointer Capture.");
1452 reason = "inbound event was dropped because there is no window with Pointer Capture";
1453 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001454 case DropReason::NOT_DROPPED: {
1455 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 }
1459
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001461 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001462 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001463 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1464 options.displayId = keyEntry.displayId;
1465 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001469 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001470 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1471 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001472 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001473 options.displayId = motionEntry.displayId;
1474 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475 synthesizeCancelationEventsForAllConnectionsLocked(options);
1476 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001477 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1478 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001479 options.displayId = motionEntry.displayId;
1480 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 synthesizeCancelationEventsForAllConnectionsLocked(options);
1482 }
1483 break;
1484 }
Chris Yef59a2f42020-10-16 12:55:26 -07001485 case EventEntry::Type::SENSOR: {
1486 break;
1487 }
arthurhungb89ccb02020-12-30 16:19:01 +08001488 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1489 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001490 break;
1491 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001492 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001493 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001494 case EventEntry::Type::CONFIGURATION_CHANGED:
1495 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001496 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001497 break;
1498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500}
1501
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001502static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001503 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1504 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505}
1506
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001507bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1508 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1509 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1510 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511}
1512
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001513bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001514 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515}
1516
1517void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001518 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001520 if (DEBUG_APP_SWITCH) {
1521 if (handled) {
1522 ALOGD("App switch has arrived.");
1523 } else {
1524 ALOGD("App switch was abandoned.");
1525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527}
1528
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001530 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531}
1532
Prabir Pradhancef936d2021-07-21 16:17:52 +00001533bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001534 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 return false;
1536 }
1537
1538 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001539 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001540 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001541 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1542 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001543 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 return true;
1545}
1546
Prabir Pradhancef936d2021-07-21 16:17:52 +00001547void InputDispatcher::postCommandLocked(Command&& command) {
1548 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549}
1550
1551void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001552 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001553 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001554 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 releaseInboundEventLocked(entry);
1556 }
1557 traceInboundQueueLengthLocked();
1558}
1559
1560void InputDispatcher::releasePendingEventLocked() {
1561 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001563 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 }
1565}
1566
Prabir Pradhan24047542023-11-02 17:14:59 +00001567void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001568 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001570 if (DEBUG_DISPATCH_CYCLE) {
1571 ALOGD("Injected inbound event was dropped.");
1572 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 }
1575 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001576 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 }
1578 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579}
1580
1581void InputDispatcher::resetKeyRepeatLocked() {
1582 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001583 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 }
1585}
1586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001588 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589
Michael Wright2e732952014-09-24 13:26:59 -07001590 uint32_t policyFlags = entry->policyFlags &
1591 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001594 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1595 currentTime, entry->deviceId, entry->source,
1596 entry->displayId, policyFlags, entry->action, entry->flags,
1597 entry->keyCode, entry->scanCode, entry->metaState,
1598 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001600 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001601 if (mTracer) {
1602 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1603 }
1604
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001605 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001607 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608}
1609
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001611 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001612 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1613 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615
1616 // Reset key repeating in case a keyboard device was added or removed or something.
1617 resetKeyRepeatLocked();
1618
1619 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001620 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1621 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001622 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001623 };
1624 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 return true;
1626}
1627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001628bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1629 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001630 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1631 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1632 entry.deviceId);
1633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634
liushenxiang42232912021-05-21 20:24:09 +08001635 // Reset key repeating in case a keyboard device was disabled or enabled.
1636 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1637 resetKeyRepeatLocked();
1638 }
1639
Michael Wrightfb04fd52022-11-24 22:31:11 +00001640 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001643
1644 // Remove all active pointers from this device
1645 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1646 touchState.removeAllPointersForDevice(entry.deviceId);
1647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 return true;
1649}
1650
Vishnu Nairad321cd2020-08-20 16:40:21 -07001651void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001652 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001653 if (mPendingEvent != nullptr) {
1654 // Move the pending event to the front of the queue. This will give the chance
1655 // for the pending event to get dispatched to the newly focused window
1656 mInboundQueue.push_front(mPendingEvent);
1657 mPendingEvent = nullptr;
1658 }
1659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001660 std::unique_ptr<FocusEntry> focusEntry =
1661 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1662 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001663
1664 // This event should go to the front of the queue, but behind all other focus events
1665 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001666 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1667 [](const std::shared_ptr<const EventEntry>& event) {
1668 return event->type == EventEntry::Type::FOCUS;
1669 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001670
1671 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001672 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001673}
1674
Prabir Pradhan24047542023-11-02 17:14:59 +00001675void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1676 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001677 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001678 if (channel == nullptr) {
1679 return; // Window has gone away
1680 }
1681 InputTarget target;
1682 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001683 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001684 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1685 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001686 std::string reason = std::string("reason=").append(entry->reason);
1687 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001688 dispatchEventLocked(currentTime, entry, {target});
1689}
1690
Prabir Pradhan99987712020-11-10 18:43:05 -08001691void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001692 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001693 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001694 dropReason = DropReason::NOT_DROPPED;
1695
Prabir Pradhan99987712020-11-10 18:43:05 -08001696 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001697 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001698
1699 if (entry->pointerCaptureRequest.enable) {
1700 // Enable Pointer Capture.
1701 if (haveWindowWithPointerCapture &&
1702 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001703 // This can happen if pointer capture is disabled and re-enabled before we notify the
1704 // app of the state change, so there is no need to notify the app.
1705 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1706 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001707 }
1708 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001709 // This can happen if a window requests capture and immediately releases capture.
1710 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001711 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001712 return;
1713 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001714 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1715 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1716 return;
1717 }
1718
Vishnu Nairc519ff72021-01-21 08:23:08 -08001719 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001720 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1721 mWindowTokenWithPointerCapture = token;
1722 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001723 // Disable Pointer Capture.
1724 // We do not check if the sequence number matches for requests to disable Pointer Capture
1725 // for two reasons:
1726 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1727 // to disable capture with the same sequence number: one generated by
1728 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1729 // Capture being disabled in InputReader.
1730 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1731 // actual Pointer Capture state that affects events being generated by input devices is
1732 // in InputReader.
1733 if (!haveWindowWithPointerCapture) {
1734 // Pointer capture was already forcefully disabled because of focus change.
1735 dropReason = DropReason::NOT_DROPPED;
1736 return;
1737 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001738 token = mWindowTokenWithPointerCapture;
1739 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001740 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001741 setPointerCaptureLocked(false);
1742 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001743 }
1744
1745 auto channel = getInputChannelLocked(token);
1746 if (channel == nullptr) {
1747 // Window has gone away, clean up Pointer Capture state.
1748 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001749 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001750 setPointerCaptureLocked(false);
1751 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001752 return;
1753 }
1754 InputTarget target;
1755 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001756 entry->dispatchInProgress = true;
1757 dispatchEventLocked(currentTime, entry, {target});
1758
1759 dropReason = DropReason::NOT_DROPPED;
1760}
1761
Prabir Pradhan24047542023-11-02 17:14:59 +00001762void InputDispatcher::dispatchTouchModeChangeLocked(
1763 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001764 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001765 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001766 if (windowHandles.empty()) {
1767 return;
1768 }
1769 const std::vector<InputTarget> inputTargets =
1770 getInputTargetsFromWindowHandlesLocked(windowHandles);
1771 if (inputTargets.empty()) {
1772 return;
1773 }
1774 entry->dispatchInProgress = true;
1775 dispatchEventLocked(currentTime, entry, inputTargets);
1776}
1777
1778std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1779 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1780 std::vector<InputTarget> inputTargets;
1781 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001782 const sp<IBinder>& token = handle->getToken();
1783 if (token == nullptr) {
1784 continue;
1785 }
1786 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1787 if (channel == nullptr) {
1788 continue; // Window has gone away
1789 }
1790 InputTarget target;
1791 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001792 inputTargets.push_back(target);
1793 }
1794 return inputTargets;
1795}
1796
Prabir Pradhan24047542023-11-02 17:14:59 +00001797bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001798 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 if (!entry->dispatchInProgress) {
1801 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1802 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1803 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1804 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001805 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 // We have seen two identical key downs in a row which indicates that the device
1807 // driver is automatically generating key repeats itself. We take note of the
1808 // repeat here, but we disable our own next key repeat timer since it is clear that
1809 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001810 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1811 // Make sure we don't get key down from a different device. If a different
1812 // device Id has same key pressed down, the new device Id will replace the
1813 // current one to hold the key repeat with repeat count reset.
1814 // In the future when got a KEY_UP on the device id, drop it and do not
1815 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1817 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001818 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 } else {
1820 // Not a repeat. Save key down state in case we do see a repeat later.
1821 resetKeyRepeatLocked();
1822 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1823 }
1824 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001825 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1826 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001827 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001828 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001829 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1830 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001831 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 resetKeyRepeatLocked();
1833 }
1834
1835 if (entry->repeatCount == 1) {
1836 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1837 } else {
1838 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1839 }
1840
1841 entry->dispatchInProgress = true;
1842
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001843 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
1845
1846 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001847 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001849 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 return false; // wait until next wakeup
1851 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001852 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 entry->interceptKeyWakeupTime = 0;
1854 }
1855
1856 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001857 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001859 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001860 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001861
1862 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1863 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1864 };
1865 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001866 // Poke user activity for keys not passed to user
1867 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 return false; // wait for the command to run
1869 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001870 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001872 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001873 if (*dropReason == DropReason::NOT_DROPPED) {
1874 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876 }
1877
1878 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001879 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001880 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1882 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001883 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001884 // Poke user activity for undispatched keys
1885 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 return true;
1887 }
1888
1889 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001890 InputEventInjectionResult injectionResult;
1891 sp<WindowInfoHandle> focusedWindow =
1892 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1893 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 return false;
1896 }
1897
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001898 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 return true;
1901 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001902 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1903
1904 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001905 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1906 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001908 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001909 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001911 if (mTracer) {
1912 ensureEventTraced(*entry);
1913 for (const auto& target : inputTargets) {
1914 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1915 }
1916 }
1917
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 // Dispatch the key.
1919 dispatchEventLocked(currentTime, entry, inputTargets);
1920 return true;
1921}
1922
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001924 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1925 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1926 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1927 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1928 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1929 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1930 entry.metaState, entry.repeatCount, entry.downTime);
1931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932}
1933
Prabir Pradhancef936d2021-07-21 16:17:52 +00001934void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001935 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001936 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001937 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1938 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1939 "source=0x%x, sensorType=%s",
1940 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001941 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001942 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001943 auto command = [this, entry]() REQUIRES(mLock) {
1944 scoped_unlock unlock(mLock);
1945
1946 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001947 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001948 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001949 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1950 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001951 };
1952 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001953}
1954
1955bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001956 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1957 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001958 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001959 }
Chris Yef59a2f42020-10-16 12:55:26 -07001960 { // acquire lock
1961 std::scoped_lock _l(mLock);
1962
1963 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001964 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001965 if (entry->type == EventEntry::Type::SENSOR) {
1966 it = mInboundQueue.erase(it);
1967 releaseInboundEventLocked(entry);
1968 }
1969 }
1970 }
1971 return true;
1972}
1973
Prabir Pradhan24047542023-11-02 17:14:59 +00001974bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1975 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001976 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001977 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001979 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 entry->dispatchInProgress = true;
1981
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001982 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
1984
1985 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001986 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001987 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001988 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1989 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 return true;
1991 }
1992
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001993 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994
1995 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001996 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001998 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 if (isPointerEvent) {
2000 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00002001
2002 if (mDragState &&
2003 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2004 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
2005 pilferPointersLocked(mDragState->dragWindow->getToken());
2006 }
2007
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002008 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002009 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002010 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
2011 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 } else {
2013 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002014 sp<WindowInfoHandle> focusedWindow =
2015 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
2016 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
2017 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002018 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2019 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2020 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002023 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 return false;
2025 }
2026
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002027 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002028 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002029 return true;
2030 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002031 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002032 CancelationOptions::Mode mode(
2033 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2034 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002035 CancelationOptions options(mode, "input event injection failed");
2036 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 return true;
2038 }
2039
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002040 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002041 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002043 if (mTracer) {
2044 ensureEventTraced(*entry);
2045 for (const auto& target : inputTargets) {
2046 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2047 }
2048 }
2049
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 dispatchEventLocked(currentTime, entry, inputTargets);
2052 return true;
2053}
2054
chaviw98318de2021-05-19 16:45:23 -05002055void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002056 bool isExiting, const int32_t rawX,
2057 const int32_t rawY) {
2058 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002059 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002060 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2061 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002062
2063 enqueueInboundEventLocked(std::move(dragEntry));
2064}
2065
Prabir Pradhan24047542023-11-02 17:14:59 +00002066void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2067 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08002068 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
2069 if (channel == nullptr) {
2070 return; // Window has gone away
2071 }
2072 InputTarget target;
2073 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08002074 entry->dispatchInProgress = true;
2075 dispatchEventLocked(currentTime, entry, {target});
2076}
2077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002079 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002080 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002081 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002082 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002083 "metaState=0x%x, buttonState=0x%x,"
2084 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002085 prefix, entry.eventTime, entry.deviceId,
2086 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2087 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2088 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2089 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002091 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002092 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002093 "x=%f, y=%f, pressure=%f, size=%f, "
2094 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2095 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002096 i, entry.pointerProperties[i].id,
2097 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002098 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2099 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2100 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2101 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2102 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2103 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2104 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2105 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2106 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109}
2110
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002111void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002112 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002113 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002114 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002115 if (DEBUG_DISPATCH_CYCLE) {
2116 ALOGD("dispatchEventToCurrentInputTargets");
2117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002119 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002120
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2122
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002125 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002126 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002127 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002128 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002129 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002131 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2132 LOG(INFO) << "Dropping event delivery to target with channel "
2133 << inputTarget.inputChannel->getName()
2134 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137 }
2138}
2139
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002140void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002141 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2142 // If the policy decides to close the app, we will get a channel removal event via
2143 // unregisterInputChannel, and will clean up the connection that way. We are already not
2144 // sending new pointers to the connection when it blocked, but focused events will continue to
2145 // pile up.
2146 ALOGW("Canceling events for %s because it is unresponsive",
2147 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002148 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002149 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002150 "application not responding");
2151 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153}
2154
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002155void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002156 if (DEBUG_FOCUS) {
2157 ALOGD("Resetting ANR timeouts.");
2158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159
2160 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002162 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163}
2164
Tiger Huang721e26f2018-07-24 22:26:19 +08002165/**
2166 * Get the display id that the given event should go to. If this event specifies a valid display id,
2167 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2168 * Focused display is the display that the user most recently interacted with.
2169 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002170int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002171 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002173 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2175 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 break;
2177 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002178 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002179 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2180 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 break;
2182 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002183 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002184 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002185 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002186 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002187 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002188 case EventEntry::Type::SENSOR:
2189 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002190 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 return ADISPLAY_ID_NONE;
2192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002193 }
2194 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2195}
2196
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002197bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2198 const char* focusedWindowName) {
2199 if (mAnrTracker.empty()) {
2200 // already processed all events that we waited for
2201 mKeyIsWaitingForEventsTimeout = std::nullopt;
2202 return false;
2203 }
2204
2205 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2206 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002207 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002208 mKeyIsWaitingForEventsTimeout = currentTime +
2209 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2210 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002211 return true;
2212 }
2213
2214 // We still have pending events, and already started the timer
2215 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2216 return true; // Still waiting
2217 }
2218
2219 // Waited too long, and some connection still hasn't processed all motions
2220 // Just send the key to the focused window
2221 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2222 focusedWindowName);
2223 mKeyIsWaitingForEventsTimeout = std::nullopt;
2224 return false;
2225}
2226
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002228 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002229 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002230 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
Tiger Huang721e26f2018-07-24 22:26:19 +08002232 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002233 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002234 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002235 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2236
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 // If there is no currently focused window and no focused application
2238 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002239 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2240 ALOGI("Dropping %s event because there is no focused window or focused application in "
2241 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002242 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002243 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
2245
Vishnu Nair062a8672021-09-03 16:07:44 -07002246 // Drop key events if requested by input feature
2247 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002248 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002249 }
2250
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002251 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2252 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2253 // start interacting with another application via touch (app switch). This code can be removed
2254 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2255 // an app is expected to have a focused window.
2256 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2257 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2258 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002259 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2260 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2261 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002262 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002263 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 ALOGW("Waiting because no window has focus but %s may eventually add a "
2265 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002266 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002267 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002268 outInjectionResult = InputEventInjectionResult::PENDING;
2269 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002270 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2271 // Already raised ANR. Drop the event
2272 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002273 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002274 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002275 } else {
2276 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002277 outInjectionResult = InputEventInjectionResult::PENDING;
2278 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002279 }
2280 }
2281
2282 // we have a valid, non-null focused window
2283 resetNoFocusedWindowTimeoutLocked();
2284
Prabir Pradhan5735a322022-04-11 17:23:34 +00002285 // Verify targeted injection.
2286 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2287 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002288 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2289 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002292 if (focusedWindowHandle->getInfo()->inputConfig.test(
2293 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002294 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002295 outInjectionResult = InputEventInjectionResult::PENDING;
2296 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002297 }
2298
2299 // If the event is a key event, then we must wait for all previous events to
2300 // complete before delivering it because previous events may have the
2301 // side-effect of transferring focus to a different window and we want to
2302 // ensure that the following keys are sent to the new window.
2303 //
2304 // Suppose the user touches a button in a window then immediately presses "A".
2305 // If the button causes a pop-up window to appear then we want to ensure that
2306 // the "A" key is delivered to the new pop-up window. This is because users
2307 // often anticipate pending UI changes when typing on a keyboard.
2308 // To obtain this behavior, we must serialize key events with respect to all
2309 // prior input events.
2310 if (entry.type == EventEntry::Type::KEY) {
2311 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002312 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002313 outInjectionResult = InputEventInjectionResult::PENDING;
2314 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002318 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2319 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320}
2321
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002322/**
2323 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2324 * that are currently unresponsive.
2325 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002326std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2327 const std::vector<Monitor>& monitors) const {
2328 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002329 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002330 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002331 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002332 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002333 if (connection == nullptr) {
2334 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002335 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002336 return false;
2337 }
2338 if (!connection->responsive) {
2339 ALOGW("Unresponsive monitor %s will not get the new gesture",
2340 connection->inputChannel->getName().c_str());
2341 return false;
2342 }
2343 return true;
2344 });
2345 return responsiveMonitors;
2346}
2347
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002348std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002349 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002350 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002351 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002353 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 // For security reasons, we defer updating the touch state until we are sure that
2355 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 const int32_t displayId = entry.displayId;
2357 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002358 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
2360 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002361 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002363 // Copy current touch state into tempTouchState.
2364 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2365 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002366 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002367 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2369 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002370 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002371 }
2372
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002373 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002374
2375 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2376 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2377 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002378 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2379 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002380 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002381 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2382 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002383 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2384 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2385 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002386 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002387
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002388 if (newGesture) {
2389 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002390 }
2391
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002392 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2393 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2394 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002397 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002398 if (wasDown) {
2399 // Started hovering, but the device is already down: reject the hover event
2400 LOG(ERROR) << "Got hover event " << entry.getDescription()
2401 << " but the device is already down " << oldState->dump();
2402 outInjectionResult = InputEventInjectionResult::FAILED;
2403 return {};
2404 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002405 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2406 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002407 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002408 }
2409
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2411 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002412 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002413 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002414 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002415 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2416 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002417 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002418 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002419 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002420
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002421 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002422 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002425 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002426 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002428 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002429 }
2430
Prabir Pradhan5735a322022-04-11 17:23:34 +00002431 // Verify targeted injection.
2432 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2433 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002434 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002435 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002436 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002437 }
2438
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002439 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002440 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002441 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2442 // New window supports splitting, but we should never split mouse events.
2443 isSplit = !isFromMouse;
2444 } else if (isSplit) {
2445 // New window does not support splitting but we have already split events.
2446 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002447 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2448 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002449 newTouchedWindowHandle = nullptr;
2450 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002451 } else {
2452 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002453 // be delivered to a new window which supports split touch. Pointers from a mouse device
2454 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002455 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002456 }
2457
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002458 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002459 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002460 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002461 // Process the foreground window first so that it is the first to receive the event.
2462 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002463 }
2464
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002465 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002466 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2467 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002468 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002469 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002470 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002471 }
2472
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002473 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002474 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002475 continue;
2476 }
2477
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002478 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002479 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002480 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002481 }
2482
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002483 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002484 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002485
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002486 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2487 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002488 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002489 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002490
2491 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002492 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002493 }
2494 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002495 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002496 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002497 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002498 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002499
2500 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002501
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002502 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002503 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2504 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002505 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002506 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002507 isDownOrPointerDown
2508 ? std::make_optional(entry.eventTime)
2509 : std::nullopt);
2510 // If this is the pointer going down and the touched window has a wallpaper
2511 // then also add the touched wallpaper windows so they are locked in for the
2512 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2513 // SCROLL because the wallpaper engine only supports touch events. We would need to
2514 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2515 // handle these events.
2516 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002517 windowHandle->getInfo()->inputConfig.test(
2518 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2519 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2520 if (wallpaper != nullptr) {
2521 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2522 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002523 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002524 if (isSplit) {
2525 wallpaperFlags |= InputTarget::Flags::SPLIT;
2526 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002527 tempTouchState.addOrUpdateWindow(wallpaper,
2528 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002529 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002530 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002531 }
2532 }
2533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002535
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002536 // If a window is already pilfering some pointers, give it this new pointer as well and
2537 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2538 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002539 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002540 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002541 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002542 // This window is already pilfering some pointers, and this new pointer is also
2543 // going to it. Therefore, take over this pointer and don't give it to anyone
2544 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002545 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002546 }
2547 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002548
2549 // Restrict all pilfered pointers to the pilfering windows.
2550 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 } else {
2552 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2553
2554 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002555 if (!tempTouchState.isDown(entry.deviceId) &&
2556 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002557 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2558 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2559 << " is not down or we previously dropped the pointer down event in "
2560 << "display " << displayId << ": " << entry.getDescription();
2561 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002562 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002563 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002566 // If the pointer is not currently hovering, then ignore the event.
2567 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2568 const int32_t pointerId = entry.pointerProperties[0].id;
2569 if (oldState == nullptr ||
2570 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2571 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2572 "display "
2573 << displayId << ": " << entry.getDescription();
2574 outInjectionResult = InputEventInjectionResult::FAILED;
2575 return {};
2576 }
2577 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2578 }
2579
arthurhung6d4bed92021-03-17 11:59:33 +08002580 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002581
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002583 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002584 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002585 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002586 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002587 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002588 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002589 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002590 sp<WindowInfoHandle> newTouchedWindowHandle =
2591 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002592
Prabir Pradhan5735a322022-04-11 17:23:34 +00002593 // Verify targeted injection.
2594 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2595 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002596 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002597 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002598 }
2599
Vishnu Nair062a8672021-09-03 16:07:44 -07002600 // Drop touch events if requested by input feature
2601 if (newTouchedWindowHandle != nullptr &&
2602 shouldDropInput(entry, newTouchedWindowHandle)) {
2603 newTouchedWindowHandle = nullptr;
2604 }
2605
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002606 if (newTouchedWindowHandle != nullptr &&
2607 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002608 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002609 oldTouchedWindowHandle->getName().c_str(),
2610 newTouchedWindowHandle->getName().c_str(), displayId);
2611
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002613 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002614 const PointerProperties& pointer = entry.pointerProperties[0];
2615 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002616
2617 const TouchedWindow& touchedWindow =
2618 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002619 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002620 InputTarget::DispatchMode::SLIPPERY_EXIT,
2621 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002622 touchedWindow.getDownTimeInTarget(entry.deviceId),
2623 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624
2625 // Make a slippery entrance into the new window.
2626 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002627 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 }
2629
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002630 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002631 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002632 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002635 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 }
2637 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002638 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002639 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002640 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 }
2642
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002643 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2644 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002645 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002646 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002647
2648 // Check if the wallpaper window should deliver the corresponding event.
2649 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002650 tempTouchState, entry.deviceId, pointer, targets);
2651 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002652 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654 }
Arthur Hung96483742022-11-15 03:30:48 +00002655
2656 // Update the pointerIds for non-splittable when it received pointer down.
2657 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2658 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002659 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002660 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2661 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002662 // Ignore drag window for it should just track one pointer.
2663 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2664 continue;
2665 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002666 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002667 }
2668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 }
2670
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002671 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002672 {
2673 std::vector<TouchedWindow> hoveringWindows =
2674 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2675 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002676 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002677 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2678 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002679 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002680 if (!target) {
2681 continue;
2682 }
2683 // Hardcode to single hovering pointer for now.
2684 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2685 pointerIds.set(entry.pointerProperties[0].id);
2686 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2687 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690
Prabir Pradhan5735a322022-04-11 17:23:34 +00002691 // Ensure that all touched windows are valid for injection.
2692 if (entry.injectionState != nullptr) {
2693 std::string errs;
2694 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002695 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2696 if (err) errs += "\n - " + *err;
2697 }
2698 if (!errs.empty()) {
2699 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002700 "%s:%s",
2701 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002702 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002703 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002704 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002705 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002706
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002707 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2708 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002710 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002711 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002712 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002713 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002714 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002715 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002716 sp<WindowInfoHandle> targetWindow =
2717 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2718 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2719 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721 }
2722 }
2723 }
2724 }
2725
Harry Cuttsb166c002023-05-09 13:06:05 +00002726 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2727 // only want the system UI to handle these gestures.
2728 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2729 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2730 if (isTouchpadNavGesture) {
2731 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2732 }
2733
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002734 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002735 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002736 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002737 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002738 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002739 continue;
2740 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002741 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002742 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002743 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002744 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002745
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002746 // During targeted injection, only allow owned targets to receive events
2747 std::erase_if(targets, [&](const InputTarget& target) {
2748 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2749 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2750 if (err) {
2751 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2752 << ": " << (*err);
2753 return true;
2754 }
2755 return false;
2756 });
2757
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002758 if (targets.empty()) {
2759 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2760 outInjectionResult = InputEventInjectionResult::FAILED;
2761 return {};
2762 }
2763
2764 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2765 // window that is actually receiving the entire gesture.
2766 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002767 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002768 })) {
2769 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2770 << entry.getDescription();
2771 outInjectionResult = InputEventInjectionResult::FAILED;
2772 return {};
2773 }
2774
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002775 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776
Prabir Pradhan502a7252023-12-01 16:11:24 +00002777 // Now that we have generated all of the input targets for this event, reset the dispatch
2778 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002779 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002780 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002781 }
2782
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002783 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002784 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002785 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002786 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002787 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002788 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002789 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002790 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2791 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002792 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2793 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2794 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 }
2796
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002797 // Save changes unless the action was scroll in which case the temporary touch
2798 // state was only valid for this one action.
2799 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002800 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002801 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002802 mTouchStatesByDisplay[displayId] = tempTouchState;
2803 } else {
2804 mTouchStatesByDisplay.erase(displayId);
2805 }
2806 }
2807
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002808 if (tempTouchState.windows.empty()) {
2809 mTouchStatesByDisplay.erase(displayId);
2810 }
2811
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002812 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813}
2814
arthurhung6d4bed92021-03-17 11:59:33 +08002815void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002816 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2817 // have an explicit reason to support it.
2818 constexpr bool isStylus = false;
2819
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002820 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002821 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002822 if (dropWindow) {
2823 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002824 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002825 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002826 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002827 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002828 }
2829 mDragState.reset();
2830}
2831
2832void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002833 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002834 return;
2835 }
2836
arthurhung6d4bed92021-03-17 11:59:33 +08002837 if (!mDragState->isStartDrag) {
2838 mDragState->isStartDrag = true;
2839 mDragState->isStylusButtonDownAtStart =
2840 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2841 }
2842
Arthur Hung54745652022-04-20 07:17:41 +00002843 // Find the pointer index by id.
2844 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002845 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002846 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2847 if (pointerProperties.id == mDragState->pointerId) {
2848 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002849 }
Arthur Hung54745652022-04-20 07:17:41 +00002850 }
arthurhung6d4bed92021-03-17 11:59:33 +08002851
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002852 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002853 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002854 }
2855
2856 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2857 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2858 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2859
2860 switch (maskedAction) {
2861 case AMOTION_EVENT_ACTION_MOVE: {
2862 // Handle the special case : stylus button no longer pressed.
2863 bool isStylusButtonDown =
2864 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2865 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2866 finishDragAndDrop(entry.displayId, x, y);
2867 return;
2868 }
2869
2870 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2871 // until we have an explicit reason to support it.
2872 constexpr bool isStylus = false;
2873
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002874 sp<WindowInfoHandle> hoverWindowHandle =
2875 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2876 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002877 // enqueue drag exit if needed.
2878 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2879 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2880 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002881 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002882 y);
2883 }
2884 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2885 }
2886 // enqueue drag location if needed.
2887 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002888 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002889 }
2890 break;
2891 }
2892
2893 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002894 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002895 break;
2896 }
2897 // The drag pointer is up.
2898 [[fallthrough]];
2899 case AMOTION_EVENT_ACTION_UP:
2900 finishDragAndDrop(entry.displayId, x, y);
2901 break;
2902 case AMOTION_EVENT_ACTION_CANCEL: {
2903 ALOGD("Receiving cancel when drag and drop.");
2904 sendDropWindowCommandLocked(nullptr, 0, 0);
2905 mDragState.reset();
2906 break;
2907 }
arthurhungb89ccb02020-12-30 16:19:01 +08002908 }
2909}
2910
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002911std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2912 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002913 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002914 std::optional<nsecs_t> firstDownTimeInTarget) const {
2915 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2916 if (inputChannel == nullptr) {
2917 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2918 return {};
2919 }
2920 InputTarget inputTarget;
2921 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002922 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002923 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002924 inputTarget.flags = targetFlags;
2925 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2926 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2927 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2928 if (displayInfoIt != mDisplayInfos.end()) {
2929 inputTarget.displayTransform = displayInfoIt->second.transform;
2930 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002931 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002932 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2933 }
2934 return inputTarget;
2935}
2936
chaviw98318de2021-05-19 16:45:23 -05002937void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002938 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002939 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002940 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002941 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002942 std::vector<InputTarget>::iterator it =
2943 std::find_if(inputTargets.begin(), inputTargets.end(),
2944 [&windowHandle](const InputTarget& inputTarget) {
2945 return inputTarget.inputChannel->getConnectionToken() ==
2946 windowHandle->getToken();
2947 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002948
chaviw98318de2021-05-19 16:45:23 -05002949 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002950
2951 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002952 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002953 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2954 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002955 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002956 return;
2957 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002958 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002959 it = inputTargets.end() - 1;
2960 }
2961
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002962 if (it->flags != targetFlags) {
2963 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2964 }
2965 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2966 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2967 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2968 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002969}
2970
2971void InputDispatcher::addPointerWindowTargetLocked(
2972 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002973 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2974 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2975 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002976 if (pointerIds.none()) {
2977 for (const auto& target : inputTargets) {
2978 LOG(INFO) << "Target: " << target;
2979 }
2980 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2981 return;
2982 }
2983 std::vector<InputTarget>::iterator it =
2984 std::find_if(inputTargets.begin(), inputTargets.end(),
2985 [&windowHandle](const InputTarget& inputTarget) {
2986 return inputTarget.inputChannel->getConnectionToken() ==
2987 windowHandle->getToken();
2988 });
2989
2990 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2991 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2992 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2993 // input targets for hovering pointers and for touching pointers.
2994 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2995 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002996 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002997 // Force the code below to create a new input target
2998 it = inputTargets.end();
2999 }
3000
3001 const WindowInfo* windowInfo = windowHandle->getInfo();
3002
3003 if (it == inputTargets.end()) {
3004 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003005 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
3006 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003007 if (!target) {
3008 return;
3009 }
3010 inputTargets.push_back(*target);
3011 it = inputTargets.end() - 1;
3012 }
3013
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003014 if (it->dispatchMode != dispatchMode) {
3015 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
3016 << ftl::enum_string(dispatchMode) << ", it=" << *it;
3017 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003018 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003019 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
3020 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003021 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003022 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003023 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003024 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3025 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003026
chaviw1ff3d1e2020-07-01 15:53:47 -07003027 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028}
3029
Michael Wright3dd60e22019-03-27 22:06:44 +00003030void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07003031 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003032 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3033 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003034
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003035 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
3036 InputTarget target;
3037 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003038 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3039 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003040 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3041 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003042 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003043 target.setDefaultPointerTransform(target.displayTransform);
3044 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
3046}
3047
Robert Carrc9bf1d32020-04-13 17:21:08 -07003048/**
3049 * Indicate whether one window handle should be considered as obscuring
3050 * another window handle. We only check a few preconditions. Actually
3051 * checking the bounds is left to the caller.
3052 */
chaviw98318de2021-05-19 16:45:23 -05003053static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3054 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003055 // Compare by token so cloned layers aren't counted
3056 if (haveSameToken(windowHandle, otherHandle)) {
3057 return false;
3058 }
3059 auto info = windowHandle->getInfo();
3060 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003061 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003062 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003063 } else if (otherInfo->alpha == 0 &&
3064 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003065 // Those act as if they were invisible, so we don't need to flag them.
3066 // We do want to potentially flag touchable windows even if they have 0
3067 // opacity, since they can consume touches and alter the effects of the
3068 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003069 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003070 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3071 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003072 } else if (info->ownerUid == otherInfo->ownerUid) {
3073 // If ownerUid is the same we don't generate occlusion events as there
3074 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003075 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003076 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003077 return false;
3078 } else if (otherInfo->displayId != info->displayId) {
3079 return false;
3080 }
3081 return true;
3082}
3083
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003084/**
3085 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3086 * untrusted, one should check:
3087 *
3088 * 1. If result.hasBlockingOcclusion is true.
3089 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3090 * BLOCK_UNTRUSTED.
3091 *
3092 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3093 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3094 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3095 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3096 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3097 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3098 *
3099 * If neither of those is true, then it means the touch can be allowed.
3100 */
3101InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003102 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3103 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003104 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003105 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003106 TouchOcclusionInfo info;
3107 info.hasBlockingOcclusion = false;
3108 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003109 info.obscuringUid = gui::Uid::INVALID;
3110 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003111 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003112 if (windowHandle == otherHandle) {
3113 break; // All future windows are below us. Exit early.
3114 }
chaviw98318de2021-05-19 16:45:23 -05003115 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003116 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3117 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003118 if (DEBUG_TOUCH_OCCLUSION) {
3119 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003120 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003121 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003122 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3123 // we perform the checks below to see if the touch can be propagated or not based on the
3124 // window's touch occlusion mode
3125 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3126 info.hasBlockingOcclusion = true;
3127 info.obscuringUid = otherInfo->ownerUid;
3128 info.obscuringPackage = otherInfo->packageName;
3129 break;
3130 }
3131 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003132 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003133 float opacity =
3134 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3135 // Given windows A and B:
3136 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3137 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3138 opacityByUid[uid] = opacity;
3139 if (opacity > info.obscuringOpacity) {
3140 info.obscuringOpacity = opacity;
3141 info.obscuringUid = uid;
3142 info.obscuringPackage = otherInfo->packageName;
3143 }
3144 }
3145 }
3146 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003147 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003148 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003149 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003150 return info;
3151}
3152
chaviw98318de2021-05-19 16:45:23 -05003153std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003154 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003155 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003156 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3157 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3158 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003159 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003160 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003161 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3162 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003163 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3164 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3165 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003166 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003167}
3168
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003169bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3170 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003171 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3172 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003173 return false;
3174 }
3175 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003176 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003177 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003178 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003179 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3180 return false;
3181 }
3182 return true;
3183}
3184
chaviw98318de2021-05-19 16:45:23 -05003185bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003186 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003188 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3189 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003190 if (windowHandle == otherHandle) {
3191 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 }
chaviw98318de2021-05-19 16:45:23 -05003193 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003194 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003195 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 return true;
3197 }
3198 }
3199 return false;
3200}
3201
chaviw98318de2021-05-19 16:45:23 -05003202bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003203 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003204 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3205 const WindowInfo* windowInfo = windowHandle->getInfo();
3206 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003207 if (windowHandle == otherHandle) {
3208 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003209 }
chaviw98318de2021-05-19 16:45:23 -05003210 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003211 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003212 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003213 return true;
3214 }
3215 }
3216 return false;
3217}
3218
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003219std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003220 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003221 if (applicationHandle != nullptr) {
3222 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003223 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 } else {
3225 return applicationHandle->getName();
3226 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003227 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003228 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232}
3233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003234void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003235 if (!isUserActivityEvent(eventEntry)) {
3236 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003237 return;
3238 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003239 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003240 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003241 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003242 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003243 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003244 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003245 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
3247 }
3248
3249 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003250 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003251 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003252 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3253 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 return;
3255 }
Josep del Riob3981622023-04-18 15:49:45 +00003256 if (windowDisablingUserActivityInfo != nullptr) {
3257 if (DEBUG_DISPATCH_CYCLE) {
3258 ALOGD("Not poking user activity: disabled by window '%s'.",
3259 windowDisablingUserActivityInfo->name.c_str());
3260 }
3261 return;
3262 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003263 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 eventType = USER_ACTIVITY_EVENT_TOUCH;
3265 }
3266 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003268 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003269 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3270 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 return;
3272 }
Josep del Riob3981622023-04-18 15:49:45 +00003273 // If the key code is unknown, we don't consider it user activity
3274 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3275 return;
3276 }
3277 // Don't inhibit events that were intercepted or are not passed to
3278 // the apps, like system shortcuts
3279 if (windowDisablingUserActivityInfo != nullptr &&
3280 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3281 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3282 if (DEBUG_DISPATCH_CYCLE) {
3283 ALOGD("Not poking user activity: disabled by window '%s'.",
3284 windowDisablingUserActivityInfo->name.c_str());
3285 }
3286 return;
3287 }
3288
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 eventType = USER_ACTIVITY_EVENT_BUTTON;
3290 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003292 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003293 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003294 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003295 break;
3296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 }
3298
Prabir Pradhancef936d2021-07-21 16:17:52 +00003299 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3300 REQUIRES(mLock) {
3301 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003302 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003303 };
3304 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305}
3306
3307void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003308 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003309 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003310 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003311 ATRACE_NAME_IF(ATRACE_ENABLED(),
3312 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3313 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003314 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003315 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003316 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003317 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003318 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003319 inputTarget.getPointerInfoString().c_str());
3320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321
3322 // Skip this event if the connection status is not normal.
3323 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003324 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003325 if (DEBUG_DISPATCH_CYCLE) {
3326 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003327 connection->getInputChannelName().c_str(),
3328 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 return;
3331 }
3332
3333 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003335 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003337 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003339 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003340 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003341 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3342 logDispatchStateLocked();
3343 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3344 "target on connection "
3345 << connection->getInputChannelName() << " for "
3346 << originalMotionEntry.getDescription();
3347 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003349 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3350 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 if (!splitMotionEntry) {
3352 return; // split event was dropped
3353 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003354 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3355 std::string reason = std::string("reason=pointer cancel on split window");
3356 android_log_event_list(LOGTAG_INPUT_CANCEL)
3357 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3358 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003359 if (DEBUG_FOCUS) {
3360 ALOGD("channel '%s' ~ Split motion event.",
3361 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003362 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003363 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003364 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3365 std::move(splitMotionEntry),
3366 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 return;
3368 }
3369 }
3370
3371 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003372 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3373 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374}
3375
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003376void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3377 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3378 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003379 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003380 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3381 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003382 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003383
hongzuo liu95785e22022-09-06 02:51:35 +00003384 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003386 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
3388 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003389 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 startDispatchCycleLocked(currentTime, connection);
3391 }
3392}
3393
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003394void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003395 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003396 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 // This is a new event.
3398 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003399 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003400 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003402 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3403 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003404 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003406 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003407 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003408 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3409 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003410 LOG(WARNING) << "channel " << connection->getInputChannelName()
3411 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 return; // skip the inconsistent event
3413 }
3414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003417 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003418 std::shared_ptr<const MotionEntry> resolvedMotion =
3419 std::static_pointer_cast<const MotionEntry>(eventEntry);
3420 {
3421 // Determine the resolved motion entry.
3422 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3423 int32_t resolvedAction = motionEntry.action;
3424 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003426 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003427 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003428 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003429 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003430 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003431 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003432 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003433 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003434 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003435 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3436 }
3437 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3438 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3439 motionEntry.displayId)) {
3440 if (DEBUG_DISPATCH_CYCLE) {
3441 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3442 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3443 "enter event";
3444 }
3445 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3446 }
3447
3448 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3449 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3450 }
3451 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3452 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3453 }
3454 if (dispatchEntry->targetFlags.test(
3455 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3456 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3457 }
3458
3459 dispatchEntry->resolvedFlags = resolvedFlags;
3460 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003461 std::optional<std::vector<PointerProperties>> usingProperties;
3462 std::optional<std::vector<PointerCoords>> usingCoords;
3463 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3464 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3465 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3466 // the dispatcher, and therefore the coordinates of this event are currently
3467 // incorrect. These events should use the coordinates of the last dispatched
3468 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3469 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3470 std::optional<std::pair<std::vector<PointerProperties>,
3471 std::vector<PointerCoords>>>
3472 pointerInfo =
3473 connection->inputState.getPointersOfLastEvent(motionEntry,
3474 hovering);
3475 if (pointerInfo) {
3476 usingProperties = pointerInfo->first;
3477 usingCoords = pointerInfo->second;
3478 }
3479 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003480 // Generate a new MotionEntry with a new eventId using the resolved action and
3481 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003482 resolvedMotion = std::make_shared<
3483 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3484 motionEntry.eventTime, motionEntry.deviceId,
3485 motionEntry.source, motionEntry.displayId,
3486 motionEntry.policyFlags, resolvedAction,
3487 motionEntry.actionButton, resolvedFlags,
3488 motionEntry.metaState, motionEntry.buttonState,
3489 motionEntry.classification, motionEntry.edgeFlags,
3490 motionEntry.xPrecision, motionEntry.yPrecision,
3491 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3492 motionEntry.downTime,
3493 usingProperties.value_or(motionEntry.pointerProperties),
3494 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003495 if (ATRACE_ENABLED()) {
3496 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3497 ") to MotionEvent(id=0x%" PRIx32 ").",
3498 motionEntry.id, resolvedMotion->id);
3499 ATRACE_NAME(message.c_str());
3500 }
3501
3502 // Set the resolved motion entry in the DispatchEntry.
3503 dispatchEntry->eventEntry = resolvedMotion;
3504 eventEntry = resolvedMotion;
3505 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003508 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3509 // devices being active at the same time in the same window, so if a new device is
3510 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003511 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003512 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003513 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003514 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003515 << connection->getInputChannelName() << " with event "
3516 << cancelEvent->getDescription();
3517 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3518 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003519 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003520
3521 // Send these cancel events to the queue before sending the event from the new
3522 // device.
3523 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3524 }
3525
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003526 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003528 LOG(WARNING) << "channel " << connection->getInputChannelName()
3529 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003530 return; // skip the inconsistent event
3531 }
3532
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003533 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3534 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003535 // Skip reporting pointer down outside focus to the policy.
3536 break;
3537 }
3538
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003539 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003540 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003541
3542 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003544 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003545 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003546 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3547 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003548 break;
3549 }
Chris Yef59a2f42020-10-16 12:55:26 -07003550 case EventEntry::Type::SENSOR: {
3551 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3552 break;
3553 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003554 case EventEntry::Type::CONFIGURATION_CHANGED:
3555 case EventEntry::Type::DEVICE_RESET: {
3556 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003557 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003558 break;
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561
3562 // Remember that we are waiting for this dispatch to complete.
3563 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003564 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 }
3566
3567 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003568 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003569 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003570}
3571
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003572/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003573 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003574 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003575 * The first role is to log input interaction with windows, which helps determine what the user was
3576 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3577 * that user started interacting with launcher window, as well as any other window that received
3578 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3579 * when the set of tokens that received the event changes. It is not logged again as long as the
3580 * user is interacting with the same windows.
3581 *
3582 * The second role is to track input device activity for metrics collection. For each input event,
3583 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3584 * input_interaction logs, the device interaction is reported even when the set of interaction
3585 * tokens do not change.
3586 *
3587 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3588 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003589 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003590void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3591 const std::vector<InputTarget>& targets) {
3592 int32_t deviceId;
3593 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003594 // Skip ACTION_UP events, and all events other than keys and motions
3595 if (entry.type == EventEntry::Type::KEY) {
3596 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3597 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3598 return;
3599 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003600 deviceId = keyEntry.deviceId;
3601 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003602 } else if (entry.type == EventEntry::Type::MOTION) {
3603 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3604 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003605 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3606 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003607 return;
3608 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003609 deviceId = motionEntry.deviceId;
3610 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003611 } else {
3612 return; // Not a key or a motion
3613 }
3614
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003615 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003616 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003617 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003618 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003619 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003620 continue; // Skip windows that receive ACTION_OUTSIDE
3621 }
3622
3623 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003624 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003625 if (connection == nullptr) {
3626 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003627 }
3628 newConnectionTokens.insert(std::move(token));
3629 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003630 if (target.windowHandle) {
3631 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3632 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003633 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003634
3635 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3636 REQUIRES(mLock) {
3637 scoped_unlock unlock(mLock);
3638 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3639 };
3640 postCommandLocked(std::move(command));
3641
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003642 if (newConnectionTokens == mInteractionConnectionTokens) {
3643 return; // no change
3644 }
3645 mInteractionConnectionTokens = newConnectionTokens;
3646
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003647 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003648 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003649 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003650 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003651 std::string message = "Interaction with: " + targetList;
3652 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003653 message += "<none>";
3654 }
3655 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3656}
3657
chaviwfd6d3512019-03-25 13:23:49 -07003658void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003659 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003660 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003661 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3662 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003663 return;
3664 }
3665
Vishnu Nairc519ff72021-01-21 08:23:08 -08003666 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003667 if (focusedToken == token) {
3668 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003669 return;
3670 }
3671
Prabir Pradhancef936d2021-07-21 16:17:52 +00003672 auto command = [this, token]() REQUIRES(mLock) {
3673 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003674 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003675 };
3676 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677}
3678
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003679status_t InputDispatcher::publishMotionEvent(Connection& connection,
3680 DispatchEntry& dispatchEntry) const {
3681 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3682 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3683
3684 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003685 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003686
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003687 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003688 // Set the X and Y offset and X and Y scale depending on the input source.
3689 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003690 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003691 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3692 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003693 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003694 scaledCoords[i] = motionEntry.pointerCoords[i];
3695 // Don't apply window scale here since we don't want scale to affect raw
3696 // coordinates. The scale will be sent back to the client and applied
3697 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003698 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003699 }
3700 usingCoords = scaledCoords;
3701 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003702 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003703 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003704 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003705 scaledCoords[i].clear();
3706 }
3707 usingCoords = scaledCoords;
3708 }
3709
3710 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3711
3712 // Publish the motion event.
3713 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003714 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3715 motionEntry.source, motionEntry.displayId, std::move(hmac),
3716 motionEntry.action, motionEntry.actionButton,
3717 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3718 motionEntry.metaState, motionEntry.buttonState,
3719 motionEntry.classification, dispatchEntry.transform,
3720 motionEntry.xPrecision, motionEntry.yPrecision,
3721 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3722 dispatchEntry.rawTransform, motionEntry.downTime,
3723 motionEntry.eventTime, motionEntry.getPointerCount(),
3724 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003725}
3726
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003728 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003729 ATRACE_NAME_IF(ATRACE_ENABLED(),
3730 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3731 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003732 if (DEBUG_DISPATCH_CYCLE) {
3733 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003736 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003737 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003739 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003740 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741
3742 // Publish the event.
3743 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003744 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3745 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003746 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3748 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003749 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003750 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3751 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003755 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003756 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3757 keyEntry.deviceId, keyEntry.source,
3758 keyEntry.displayId, std::move(hmac),
3759 keyEntry.action, dispatchEntry->resolvedFlags,
3760 keyEntry.keyCode, keyEntry.scanCode,
3761 keyEntry.metaState, keyEntry.repeatCount,
3762 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003763 if (mTracer) {
3764 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3765 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003766 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
3768
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003769 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003770 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003771 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3772 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003773 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003774 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003775 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003776 if (mTracer) {
3777 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3778 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 break;
3780 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003781
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003782 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003783 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003784 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003786 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003787 break;
3788 }
3789
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003790 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3791 const TouchModeEntry& touchModeEntry =
3792 static_cast<const TouchModeEntry&>(eventEntry);
3793 status = connection->inputPublisher
3794 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3795 touchModeEntry.inTouchMode);
3796
3797 break;
3798 }
3799
Prabir Pradhan99987712020-11-10 18:43:05 -08003800 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3801 const auto& captureEntry =
3802 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3803 status = connection->inputPublisher
3804 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003805 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003806 break;
3807 }
3808
arthurhungb89ccb02020-12-30 16:19:01 +08003809 case EventEntry::Type::DRAG: {
3810 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3811 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3812 dragEntry.id, dragEntry.x,
3813 dragEntry.y,
3814 dragEntry.isExiting);
3815 break;
3816 }
3817
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003818 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003819 case EventEntry::Type::DEVICE_RESET:
3820 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003821 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003822 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003823 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 }
3826
3827 // Check the result.
3828 if (status) {
3829 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003830 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 "This is unexpected because the wait queue is empty, so the pipe "
3833 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003834 "event to it, status=%s(%d)",
3835 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3836 status);
Harry Cutts33476232023-01-30 19:57:29 +00003837 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 } else {
3839 // Pipe is full and we are waiting for the app to finish process some events
3840 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003841 if (DEBUG_DISPATCH_CYCLE) {
3842 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3843 "waiting for the application to catch up",
3844 connection->getInputChannelName().c_str());
3845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 }
3847 } else {
3848 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003849 "status=%s(%d)",
3850 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3851 status);
Harry Cutts33476232023-01-30 19:57:29 +00003852 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 }
3854 return;
3855 }
3856
3857 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003858 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3859 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3860 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003861 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003862 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003863 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003864 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003865 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 }
3867}
3868
chaviw09c8d2d2020-08-24 15:48:26 -07003869std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3870 size_t size;
3871 switch (event.type) {
3872 case VerifiedInputEvent::Type::KEY: {
3873 size = sizeof(VerifiedKeyEvent);
3874 break;
3875 }
3876 case VerifiedInputEvent::Type::MOTION: {
3877 size = sizeof(VerifiedMotionEvent);
3878 break;
3879 }
3880 }
3881 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3882 return mHmacKeyManager.sign(start, size);
3883}
3884
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003885const std::array<uint8_t, 32> InputDispatcher::getSignature(
3886 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003887 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003888 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003889 // Only sign events up and down events as the purely move events
3890 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003891 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003892 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003893
3894 VerifiedMotionEvent verifiedEvent =
3895 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3896 verifiedEvent.actionMasked = actionMasked;
3897 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3898 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003899}
3900
3901const std::array<uint8_t, 32> InputDispatcher::getSignature(
3902 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3903 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3904 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003905 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003906}
3907
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003909 const std::shared_ptr<Connection>& connection,
3910 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003911 if (DEBUG_DISPATCH_CYCLE) {
3912 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3913 connection->getInputChannelName().c_str(), seq, toString(handled));
3914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003916 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 return;
3918 }
3919
3920 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003921 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3922 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3923 };
3924 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925}
3926
3927void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003928 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003929 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003930 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003931 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3932 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
3935 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003936 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003937 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003938 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003939 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940
3941 // The connection appears to be unrecoverably broken.
3942 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003943 if (connection->status == Connection::Status::NORMAL) {
3944 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945
3946 if (notify) {
3947 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003948 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3949 connection->getInputChannelName().c_str());
3950
3951 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003952 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003953 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003954 };
3955 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
3957 }
3958}
3959
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003960void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003961 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003962 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003963 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 }
3965}
3966
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003967void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003969 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971}
3972
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003973int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3974 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003975 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003976 if (connection == nullptr) {
3977 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3978 connectionToken.get(), events);
3979 return 0; // remove the callback
3980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003982 bool notify;
3983 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3984 if (!(events & ALOOPER_EVENT_INPUT)) {
3985 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3986 "events=0x%x",
3987 connection->getInputChannelName().c_str(), events);
3988 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
3990
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003991 nsecs_t currentTime = now();
3992 bool gotOne = false;
3993 status_t status = OK;
3994 for (;;) {
3995 Result<InputPublisher::ConsumerResponse> result =
3996 connection->inputPublisher.receiveConsumerResponse();
3997 if (!result.ok()) {
3998 status = result.error().code();
3999 break;
4000 }
4001
4002 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
4003 const InputPublisher::Finished& finish =
4004 std::get<InputPublisher::Finished>(*result);
4005 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
4006 finish.consumeTime);
4007 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004008 if (shouldReportMetricsForConnection(*connection)) {
4009 const InputPublisher::Timeline& timeline =
4010 std::get<InputPublisher::Timeline>(*result);
4011 mLatencyTracker
4012 .trackGraphicsLatency(timeline.inputEventId,
4013 connection->inputChannel->getConnectionToken(),
4014 std::move(timeline.graphicsTimeline));
4015 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004016 }
4017 gotOne = true;
4018 }
4019 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004020 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004021 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 return 1;
4023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 }
4025
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004026 notify = status != DEAD_OBJECT || !connection->monitor;
4027 if (notify) {
4028 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4029 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4030 status);
4031 }
4032 } else {
4033 // Monitor channels are never explicitly unregistered.
4034 // We do it automatically when the remote endpoint is closed so don't warn about them.
4035 const bool stillHaveWindowHandle =
4036 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
4037 notify = !connection->monitor && stillHaveWindowHandle;
4038 if (notify) {
4039 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4040 connection->getInputChannelName().c_str(), events);
4041 }
4042 }
4043
4044 // Remove the channel.
4045 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
4046 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047}
4048
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004051 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00004052 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 }
4054}
4055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004057 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004058 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004059 for (const Monitor& monitor : monitors) {
4060 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004061 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004062 }
4063}
4064
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004066 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004067 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004068 if (connection == nullptr) {
4069 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004071
4072 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073}
4074
4075void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004076 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004077 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 return;
4079 }
4080
4081 nsecs_t currentTime = now();
4082
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004083 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004084 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004086 if (cancelationEvents.empty()) {
4087 return;
4088 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004089
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004090 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4091 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004092 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004094 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004095 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004096
Arthur Hungb3307ee2021-10-14 10:57:37 +00004097 std::string reason = std::string("reason=").append(options.reason);
4098 android_log_event_list(LOGTAG_INPUT_CANCEL)
4099 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4100
hongzuo liu95785e22022-09-06 02:51:35 +00004101 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004102 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004103 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00004104 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004105
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004106 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004107 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004108 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004109
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004110 switch (cancelationEventEntry->type) {
4111 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004112 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004113 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4114 ? std::make_optional(keyEntry.displayId)
4115 : std::nullopt;
4116 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004117 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4118 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004119 } else {
4120 targets.emplace_back(fallbackTarget);
4121 }
4122 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004123 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004125 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004126 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004127 const std::optional<int32_t> targetDisplay =
4128 motionEntry.displayId != ADISPLAY_ID_NONE
4129 ? std::make_optional(motionEntry.displayId)
4130 : std::nullopt;
4131 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004132 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004133 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004134 pointerIndex++) {
4135 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4136 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004137 if (mDragState && mDragState->dragWindow->getToken() == token &&
4138 pointerIds.test(mDragState->pointerId)) {
4139 LOG(INFO) << __func__
4140 << ": Canceling drag and drop because the pointers for the drag "
4141 "window are being canceled.";
4142 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4143 mDragState.reset();
4144 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004145 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4146 ftl::Flags<InputTarget::Flags>(), pointerIds,
4147 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004148 } else {
4149 targets.emplace_back(fallbackTarget);
4150 const auto it = mDisplayInfos.find(motionEntry.displayId);
4151 if (it != mDisplayInfos.end()) {
4152 targets.back().displayTransform = it->second.transform;
4153 targets.back().setDefaultPointerTransform(it->second.transform);
4154 }
4155 }
4156 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004157 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004159 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004160 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004161 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4162 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004163 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004164 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004165 break;
4166 }
4167 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004168 case EventEntry::Type::DEVICE_RESET:
4169 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004170 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004171 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004172 break;
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004176 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004177 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004179
hongzuo liu95785e22022-09-06 02:51:35 +00004180 // If the outbound queue was previously empty, start the dispatch cycle going.
4181 if (wasEmpty && !connection->outboundQueue.empty()) {
4182 startDispatchCycleLocked(currentTime, connection);
4183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184}
4185
Svet Ganov5d3bc372020-01-26 23:11:07 -08004186void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004187 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004188 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004189 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004190 return;
4191 }
4192
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004193 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004194 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195
4196 if (downEvents.empty()) {
4197 return;
4198 }
4199
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004200 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4202 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004203 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004204
chaviw98318de2021-05-19 16:45:23 -05004205 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004206 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004207
hongzuo liu95785e22022-09-06 02:51:35 +00004208 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004209 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004210 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004211 switch (downEventEntry->type) {
4212 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004213 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4214 if (windowHandle != nullptr) {
4215 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004216 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004217 pointerIndex++) {
4218 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4219 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004220 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4221 targetFlags, pointerIds, motionEntry.downTime,
4222 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004223 } else {
4224 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4225 .flags = targetFlags});
4226 const auto it = mDisplayInfos.find(motionEntry.displayId);
4227 if (it != mDisplayInfos.end()) {
4228 targets.back().displayTransform = it->second.transform;
4229 targets.back().setDefaultPointerTransform(it->second.transform);
4230 }
4231 }
4232 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233 break;
4234 }
4235
4236 case EventEntry::Type::KEY:
4237 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004238 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004239 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004240 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004241 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004242 case EventEntry::Type::SENSOR:
4243 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004244 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004245 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246 break;
4247 }
4248 }
4249
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004250 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004251 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004252 }
4253
hongzuo liu95785e22022-09-06 02:51:35 +00004254 // If the outbound queue was previously empty, start the dispatch cycle going.
4255 if (wasEmpty && !connection->outboundQueue.empty()) {
4256 startDispatchCycleLocked(downTime, connection);
4257 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004258}
4259
Arthur Hungc539dbb2022-12-08 07:45:36 +00004260void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4261 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4262 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004263 std::shared_ptr<Connection> wallpaperConnection =
4264 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004265 if (wallpaperConnection != nullptr) {
4266 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4267 }
4268 }
4269}
4270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004272 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4273 nsecs_t splitDownTime) {
4274 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
4276 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004277 std::vector<PointerProperties> splitPointerProperties;
4278 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004280 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 uint32_t splitPointerCount = 0;
4282
4283 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004286 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004288 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004290 splitPointerProperties.push_back(pointerProperties);
4291 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 splitPointerCount += 1;
4293 }
4294 }
4295
4296 if (splitPointerCount != pointerIds.count()) {
4297 // This is bad. We are missing some of the pointers that we expected to deliver.
4298 // Most likely this indicates that we received an ACTION_MOVE events that has
4299 // different pointer ids than we expected based on the previous ACTION_DOWN
4300 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4301 // in this way.
4302 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004303 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004304 "a broken sequence of pointer ids from the input device: %s",
4305 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004306 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004309 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4312 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004313 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004315 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004317 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 if (pointerIds.count() == 1) {
4319 // The first/last pointer went down/up.
4320 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004322 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4323 ? AMOTION_EVENT_ACTION_CANCEL
4324 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 } else {
4326 // A secondary pointer went down/up.
4327 uint32_t splitPointerIndex = 0;
4328 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4329 splitPointerIndex += 1;
4330 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 action = maskedAction |
4332 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334 } else {
4335 // An unrelated pointer changed.
4336 action = AMOTION_EVENT_ACTION_MOVE;
4337 }
4338 }
4339
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004340 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4341 logDispatchStateLocked();
4342 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4343 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4344 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004345 }
4346
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004347 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004348 ATRACE_NAME_IF(ATRACE_ENABLED(),
4349 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4350 ").",
4351 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004352 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004353 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4354 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004355 originalMotionEntry.deviceId, originalMotionEntry.source,
4356 originalMotionEntry.displayId,
4357 originalMotionEntry.policyFlags, action,
4358 originalMotionEntry.actionButton,
4359 originalMotionEntry.flags, originalMotionEntry.metaState,
4360 originalMotionEntry.buttonState,
4361 originalMotionEntry.classification,
4362 originalMotionEntry.edgeFlags,
4363 originalMotionEntry.xPrecision,
4364 originalMotionEntry.yPrecision,
4365 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004366 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004367 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 return splitMotionEntry;
4370}
4371
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004372void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4373 std::scoped_lock _l(mLock);
4374 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4375}
4376
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004377void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004378 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +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
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004384 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004386 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004387 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004388 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 } // release lock
4390
4391 if (needWake) {
4392 mLooper->wake();
4393 }
4394}
4395
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004396void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004397 ALOGD_IF(debugInboundEventDetails(),
4398 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4399 ", deviceId=%d, source=%s, displayId=%" PRId32
4400 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4401 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004402 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4403 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4404 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004405 Result<void> keyCheck = validateKeyEvent(args.action);
4406 if (!keyCheck.ok()) {
4407 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 return;
4409 }
4410
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004411 uint32_t policyFlags = args.policyFlags;
4412 int32_t flags = args.flags;
4413 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004414 // InputDispatcher tracks and generates key repeats on behalf of
4415 // whatever notifies it, so repeatCount should always be set to 0
4416 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4418 policyFlags |= POLICY_FLAG_VIRTUAL;
4419 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 if (policyFlags & POLICY_FLAG_FUNCTION) {
4422 metaState |= AMETA_FUNCTION_ON;
4423 }
4424
4425 policyFlags |= POLICY_FLAG_TRUSTED;
4426
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004427 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004429 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4430 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4431 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432
Michael Wright2b3c3302018-03-02 17:19:13 +00004433 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004434 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004435 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4436 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439
Antonio Kantekf16f2832021-09-28 04:39:20 +00004440 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 { // acquire lock
4442 mLock.lock();
4443
4444 if (shouldSendKeyToInputFilterLocked(args)) {
4445 mLock.unlock();
4446
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004447 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004448 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 return; // event was consumed by the filter
4450 }
4451
4452 mLock.lock();
4453 }
4454
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004455 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004456 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4457 args.deviceId, args.source, args.displayId, policyFlags,
4458 args.action, flags, keyCode, args.scanCode, metaState,
4459 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004460 if (mTracer) {
4461 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004464 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 mLock.unlock();
4466 } // release lock
4467
4468 if (needWake) {
4469 mLooper->wake();
4470 }
4471}
4472
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004473bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 return mInputFilterEnabled;
4475}
4476
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004477void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004478 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004479 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004480 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004481 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004482 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4483 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004484 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4485 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4486 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4487 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4488 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004489 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004490 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4491 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492 i, args.pointerProperties[i].id,
4493 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4494 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4495 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4496 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4497 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4498 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4499 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4500 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4501 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4502 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004505
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004506 Result<void> motionCheck =
4507 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4508 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004509 if (!motionCheck.ok()) {
4510 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4511 return;
4512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004514 if (DEBUG_VERIFY_EVENTS) {
4515 auto [it, _] =
4516 mVerifiersByDisplay.try_emplace(args.displayId,
4517 StringPrintf("display %" PRId32, args.displayId));
4518 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004519 it->second.processMovement(args.deviceId, args.source, args.action,
4520 args.getPointerCount(), args.pointerProperties.data(),
4521 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004522 if (!result.ok()) {
4523 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4524 }
4525 }
4526
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004527 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004529
4530 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004531 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4532 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004533 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4534 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004535 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537
Antonio Kantekf16f2832021-09-28 04:39:20 +00004538 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 { // acquire lock
4540 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004541 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4542 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4543 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004544 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004545 if (touchStateIt != mTouchStatesByDisplay.end()) {
4546 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004547 if (touchState.hasTouchingPointers(args.deviceId) ||
4548 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004549 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4550 }
4551 }
4552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
4554 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004555 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004556 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004557 displayTransform = it->second.transform;
4558 }
4559
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 mLock.unlock();
4561
4562 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004563 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4564 args.action, args.actionButton, args.flags, args.edgeFlags,
4565 args.metaState, args.buttonState, args.classification,
4566 displayTransform, args.xPrecision, args.yPrecision,
4567 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004568 args.downTime, args.eventTime, args.getPointerCount(),
4569 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
4571 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004572 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573 return; // event was consumed by the filter
4574 }
4575
4576 mLock.lock();
4577 }
4578
4579 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004580 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004581 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4582 args.deviceId, args.source, args.displayId,
4583 policyFlags, args.action, args.actionButton,
4584 args.flags, args.metaState, args.buttonState,
4585 args.classification, args.edgeFlags, args.xPrecision,
4586 args.yPrecision, args.xCursorPosition,
4587 args.yCursorPosition, args.downTime,
4588 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004589 if (mTracer) {
4590 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004593 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4594 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004595 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004596 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004597 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4598 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4599 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004600 }
4601
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004602 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 mLock.unlock();
4604 } // release lock
4605
4606 if (needWake) {
4607 mLooper->wake();
4608 }
4609}
4610
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004612 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004613 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4614 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004615 args.id, args.eventTime, args.deviceId, args.source,
4616 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004617 }
Chris Yef59a2f42020-10-16 12:55:26 -07004618
Antonio Kantekf16f2832021-09-28 04:39:20 +00004619 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004620 { // acquire lock
4621 mLock.lock();
4622
4623 // Just enqueue a new sensor event.
4624 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004625 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4626 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4627 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004628
4629 needWake = enqueueInboundEventLocked(std::move(newEntry));
4630 mLock.unlock();
4631 } // release lock
4632
4633 if (needWake) {
4634 mLooper->wake();
4635 }
4636}
4637
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004638void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004639 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004640 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4641 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004642 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004643 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004644}
4645
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004646bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004647 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648}
4649
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004650void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004651 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004652 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4653 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004654 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004657 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004659 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660}
4661
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004662void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004663 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004664 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4665 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667
Antonio Kantekf16f2832021-09-28 04:39:20 +00004668 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004670 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004672 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004673 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004674 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004675
4676 for (auto& [_, verifier] : mVerifiersByDisplay) {
4677 verifier.resetDevice(args.deviceId);
4678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 } // release lock
4680
4681 if (needWake) {
4682 mLooper->wake();
4683 }
4684}
4685
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004686void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004687 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004688 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4689 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004690 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004691
Antonio Kantekf16f2832021-09-28 04:39:20 +00004692 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004693 { // acquire lock
4694 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004695 auto entry =
4696 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004697 needWake = enqueueInboundEventLocked(std::move(entry));
4698 } // release lock
4699
4700 if (needWake) {
4701 mLooper->wake();
4702 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004703}
4704
Prabir Pradhan5735a322022-04-11 17:23:34 +00004705InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004706 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004707 InputEventInjectionSync syncMode,
4708 std::chrono::milliseconds timeout,
4709 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004710 Result<void> eventValidation = validateInputEvent(*event);
4711 if (!eventValidation.ok()) {
4712 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4713 return InputEventInjectionResult::FAILED;
4714 }
4715
Prabir Pradhan65613802023-02-22 23:36:58 +00004716 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004717 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4718 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4719 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4720 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004721 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004722 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Prabir Pradhan5735a322022-04-11 17:23:34 +00004724 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004726 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004727 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4728 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4729 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4730 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4731 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004732 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004733 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004734 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004735 }
4736
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004737 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4738 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4739
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004740 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004742 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004743 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004744 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004745 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004746 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4747 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4748 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004749 int32_t keyCode = incomingKey.getKeyCode();
4750 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004751 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004752 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004753 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4754 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4755 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4758 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004759 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004760
4761 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4762 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004763 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4765 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4766 std::to_string(t.duration().count()).c_str());
4767 }
4768 }
4769
4770 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004771 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004772 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4773 incomingKey.getEventTime(), resolvedDeviceId,
4774 incomingKey.getSource(), incomingKey.getDisplayId(),
4775 policyFlags, action, flags, keyCode,
4776 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004777 incomingKey.getRepeatCount(),
4778 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004779 if (mTracer) {
4780 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4781 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004782 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004783 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 }
4785
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004786 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004787 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004788 const bool isPointerEvent =
4789 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4790 // If a pointer event has no displayId specified, inject it to the default display.
4791 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4792 ? ADISPLAY_ID_DEFAULT
4793 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004794 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004795
4796 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004797 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004799 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4800 motionEvent.getAction(), eventTime,
4801 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4803 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4804 std::to_string(t.duration().count()).c_str());
4805 }
4806 }
4807
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004808 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4809 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4810 }
4811
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004813 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004814 const size_t pointerCount = motionEvent.getPointerCount();
4815 const std::vector<PointerProperties>
4816 pointerProperties(motionEvent.getPointerProperties(),
4817 motionEvent.getPointerProperties() + pointerCount);
4818
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004819 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004820 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004821 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4822 *sampleEventTimes, resolvedDeviceId,
4823 motionEvent.getSource(), displayId, policyFlags,
4824 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004825 motionEvent.getActionButton(), flags,
4826 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004827 motionEvent.getButtonState(),
4828 motionEvent.getClassification(),
4829 motionEvent.getEdgeFlags(),
4830 motionEvent.getXPrecision(),
4831 motionEvent.getYPrecision(),
4832 motionEvent.getRawXCursorPosition(),
4833 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004834 motionEvent.getDownTime(), pointerProperties,
4835 std::vector<PointerCoords>(samplePointerCoords,
4836 samplePointerCoords +
4837 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004838 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004839 if (mTracer) {
4840 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4841 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004842 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004843 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004845 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004846 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004847 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4848 resolvedDeviceId, motionEvent.getSource(), displayId,
4849 policyFlags, motionEvent.getAction(),
4850 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004851 motionEvent.getMetaState(), motionEvent.getButtonState(),
4852 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4853 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4854 motionEvent.getRawXCursorPosition(),
4855 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4856 pointerProperties,
4857 std::vector<PointerCoords>(samplePointerCoords,
4858 samplePointerCoords +
4859 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004860 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4861 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004862 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004863 }
4864 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004867 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004868 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004869 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 }
4871
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004873 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004874 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004875 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004876 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004877 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004878 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 }
4880
4881 mLock.unlock();
4882
4883 if (needWake) {
4884 mLooper->wake();
4885 }
4886
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004887 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004889 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004891 if (syncMode == InputEventInjectionSync::NONE) {
4892 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 } else {
4894 for (;;) {
4895 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004896 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 break;
4898 }
4899
4900 nsecs_t remainingTimeout = endTime - now();
4901 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004902 if (DEBUG_INJECTION) {
4903 ALOGD("injectInputEvent - Timed out waiting for injection result "
4904 "to become available.");
4905 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004906 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 break;
4908 }
4909
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004910 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 }
4912
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004913 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4914 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004916 if (DEBUG_INJECTION) {
4917 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4918 injectionState->pendingForegroundDispatches);
4919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 nsecs_t remainingTimeout = endTime - now();
4921 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004922 if (DEBUG_INJECTION) {
4923 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4924 "dispatches to finish.");
4925 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004926 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 break;
4928 }
4929
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004930 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 }
4932 }
4933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 } // release lock
4935
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004936 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004937 LOG(INFO) << "injectInputEvent - Finished with result "
4938 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940
4941 return injectionResult;
4942}
4943
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004944std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004945 std::array<uint8_t, 32> calculatedHmac;
4946 std::unique_ptr<VerifiedInputEvent> result;
4947 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004948 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004949 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4950 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4951 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004952 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004953 break;
4954 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004955 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004956 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4957 VerifiedMotionEvent verifiedMotionEvent =
4958 verifiedMotionEventFromMotionEvent(motionEvent);
4959 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004960 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004961 break;
4962 }
4963 default: {
4964 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4965 return nullptr;
4966 }
4967 }
4968 if (calculatedHmac == INVALID_HMAC) {
4969 return nullptr;
4970 }
tyiu1573a672023-02-21 22:38:32 +00004971 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004972 return nullptr;
4973 }
4974 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004975}
4976
Prabir Pradhan24047542023-11-02 17:14:59 +00004977void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004978 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004979 if (!entry.injectionState) {
4980 // Not an injected event.
4981 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004983
4984 InjectionState& injectionState = *entry.injectionState;
4985 if (DEBUG_INJECTION) {
4986 LOG(INFO) << "Setting input event injection result to "
4987 << ftl::enum_string(injectionResult);
4988 }
4989
4990 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4991 // Log the outcome since the injector did not wait for the injection result.
4992 switch (injectionResult) {
4993 case InputEventInjectionResult::SUCCEEDED:
4994 ALOGV("Asynchronous input event injection succeeded.");
4995 break;
4996 case InputEventInjectionResult::TARGET_MISMATCH:
4997 ALOGV("Asynchronous input event injection target mismatch.");
4998 break;
4999 case InputEventInjectionResult::FAILED:
5000 ALOGW("Asynchronous input event injection failed.");
5001 break;
5002 case InputEventInjectionResult::TIMED_OUT:
5003 ALOGW("Asynchronous input event injection timed out.");
5004 break;
5005 case InputEventInjectionResult::PENDING:
5006 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5007 break;
5008 }
5009 }
5010
5011 injectionState.injectionResult = injectionResult;
5012 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013}
5014
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005015void InputDispatcher::transformMotionEntryForInjectionLocked(
5016 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005017 // Input injection works in the logical display coordinate space, but the input pipeline works
5018 // display space, so we need to transform the injected events accordingly.
5019 const auto it = mDisplayInfos.find(entry.displayId);
5020 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005021 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005022
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005023 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5024 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5025 const vec2 cursor =
5026 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5027 {entry.xCursorPosition, entry.yCursorPosition});
5028 entry.xCursorPosition = cursor.x;
5029 entry.yCursorPosition = cursor.y;
5030 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005031 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005032 entry.pointerCoords[i] =
5033 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5034 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005035 }
5036}
5037
Prabir Pradhan24047542023-11-02 17:14:59 +00005038void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005039 if (entry.injectionState) {
5040 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 }
5042}
5043
Prabir Pradhan24047542023-11-02 17:14:59 +00005044void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005045 if (entry.injectionState) {
5046 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005048 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005049 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 }
5051 }
5052}
5053
chaviw98318de2021-05-19 16:45:23 -05005054const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005055 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005056 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005057 auto it = mWindowHandlesByDisplay.find(displayId);
5058 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005059}
5060
chaviw98318de2021-05-19 16:45:23 -05005061sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005062 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005063 if (windowHandleToken == nullptr) {
5064 return nullptr;
5065 }
5066
Prabir Pradhan16463382023-10-12 23:03:19 +00005067 if (!displayId) {
5068 // Look through all displays.
5069 for (auto& it : mWindowHandlesByDisplay) {
5070 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5071 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5072 if (windowHandle->getToken() == windowHandleToken) {
5073 return windowHandle;
5074 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005077 return nullptr;
5078 }
5079
Prabir Pradhan16463382023-10-12 23:03:19 +00005080 // Only look through the requested display.
5081 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005082 if (windowHandle->getToken() == windowHandleToken) {
5083 return windowHandle;
5084 }
5085 }
5086 return nullptr;
5087}
5088
chaviw98318de2021-05-19 16:45:23 -05005089sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5090 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005091 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005092 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5093 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005094 if (handle->getId() == windowHandle->getId() &&
5095 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005096 if (windowHandle->getInfo()->displayId != it.first) {
5097 ALOGE("Found window %s in display %" PRId32
5098 ", but it should belong to display %" PRId32,
5099 windowHandle->getName().c_str(), it.first,
5100 windowHandle->getInfo()->displayId);
5101 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005102 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 }
5105 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005106 return nullptr;
5107}
5108
chaviw98318de2021-05-19 16:45:23 -05005109sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005110 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5111 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112}
5113
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005114ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5115 auto displayInfoIt = mDisplayInfos.find(displayId);
5116 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5117 : kIdentityTransform;
5118}
5119
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005120bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5121 const MotionEntry& motionEntry) const {
5122 const WindowInfo& info = *window->getInfo();
5123
5124 // Skip spy window targets that are not valid for targeted injection.
5125 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005126 return false;
5127 }
5128
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005129 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5130 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5131 return false;
5132 }
5133
5134 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5135 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5136 window->getName().c_str());
5137 return false;
5138 }
5139
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005140 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005142 ALOGW("Not sending touch to %s because there's no corresponding connection",
5143 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005144 return false;
5145 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005146
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005147 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005148 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005149 return false;
5150 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005151
5152 // Drop events that can't be trusted due to occlusion
5153 const auto [x, y] = resolveTouchedPosition(motionEntry);
5154 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5155 if (!isTouchTrustedLocked(occlusionInfo)) {
5156 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005157 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005158 for (const auto& log : occlusionInfo.debugInfo) {
5159 ALOGD("%s", log.c_str());
5160 }
5161 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005162 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5163 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005164 return false;
5165 }
5166
5167 // Drop touch events if requested by input feature
5168 if (shouldDropInput(motionEntry, window)) {
5169 return false;
5170 }
5171
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005172 // Ignore touches if stylus is down anywhere on screen
5173 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5174 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5175 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5176 return false;
5177 }
5178
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005179 return true;
5180}
5181
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005182std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5183 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005184 auto connectionIt = mConnectionsByToken.find(token);
5185 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005186 return nullptr;
5187 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005188 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005189}
5190
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005191void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005192 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5193 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005194 // Remove all handles on a display if there are no windows left.
5195 mWindowHandlesByDisplay.erase(displayId);
5196 return;
5197 }
5198
5199 // Since we compare the pointer of input window handles across window updates, we need
5200 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005201 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5202 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5203 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005204 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005205 }
5206
chaviw98318de2021-05-19 16:45:23 -05005207 std::vector<sp<WindowInfoHandle>> newHandles;
5208 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005209 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005210 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005211 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005212 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005213 const bool canReceiveInput =
5214 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5215 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005216 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005217 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005218 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005219 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005220 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005221 }
5222
5223 if (info->displayId != displayId) {
5224 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5225 handle->getName().c_str(), displayId, info->displayId);
5226 continue;
5227 }
5228
Robert Carredd13602020-04-13 17:24:34 -07005229 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5230 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005231 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005232 oldHandle->updateFrom(handle);
5233 newHandles.push_back(oldHandle);
5234 } else {
5235 newHandles.push_back(handle);
5236 }
5237 }
5238
5239 // Insert or replace
5240 mWindowHandlesByDisplay[displayId] = newHandles;
5241}
5242
Arthur Hungb92218b2018-08-14 12:00:21 +08005243/**
5244 * Called from InputManagerService, update window handle list by displayId that can receive input.
5245 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5246 * If set an empty list, remove all handles from the specific display.
5247 * For focused handle, check if need to change and send a cancel event to previous one.
5248 * For removed handle, check if need to send a cancel event if already in touch.
5249 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005250void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005251 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005252 if (DEBUG_FOCUS) {
5253 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005254 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005255 windowList += iwh->getName() + " ";
5256 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005257 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259
Prabir Pradhand65552b2021-10-07 11:23:50 -07005260 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005261 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005262 const WindowInfo& info = *window->getInfo();
5263
5264 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005265 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005266 if (noInputWindow && window->getToken() != nullptr) {
5267 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5268 window->getName().c_str());
5269 window->releaseChannel();
5270 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005271
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005272 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005273 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5274 !info.inputConfig.test(
5275 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005276 "%s has feature SPY, but is not a trusted overlay.",
5277 window->getName().c_str());
5278
Prabir Pradhand65552b2021-10-07 11:23:50 -07005279 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005280 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5281 !info.inputConfig.test(
5282 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005283 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5284 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005285 }
5286
Arthur Hung72d8dc32020-03-28 00:48:39 +00005287 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005288 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289
chaviw98318de2021-05-19 16:45:23 -05005290 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005291
chaviw98318de2021-05-19 16:45:23 -05005292 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005293
Vishnu Nairc519ff72021-01-21 08:23:08 -08005294 std::optional<FocusResolver::FocusChanges> changes =
5295 mFocusResolver.setInputWindows(displayId, windowHandles);
5296 if (changes) {
5297 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005300 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5301 mTouchStatesByDisplay.find(displayId);
5302 if (stateIt != mTouchStatesByDisplay.end()) {
5303 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005304 for (size_t i = 0; i < state.windows.size();) {
5305 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005306 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005307 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5308 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005309 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005310 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5311 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005312 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005313 "touched window was removed");
5314 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005315 // Since we are about to drop the touch, cancel the events for the wallpaper as
5316 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005317 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005318 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5319 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005320 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005321 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005324 state.windows.erase(state.windows.begin() + i);
5325 } else {
5326 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328 }
arthurhungb89ccb02020-12-30 16:19:01 +08005329
arthurhung6d4bed92021-03-17 11:59:33 +08005330 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005331 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005332 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005333 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005334 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005335 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5336 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005337 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005338 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005339 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005340
Arthur Hung72d8dc32020-03-28 00:48:39 +00005341 // Release information for windows that are no longer present.
5342 // This ensures that unused input channels are released promptly.
5343 // Otherwise, they might stick around until the window handle is destroyed
5344 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005345 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005346 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005347 if (DEBUG_FOCUS) {
5348 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005349 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005350 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005351 }
chaviw291d88a2019-02-14 10:33:58 -08005352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353}
5354
5355void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005356 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005357 if (DEBUG_FOCUS) {
5358 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5359 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5360 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005361 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005362 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005363 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 } // release lock
5365
5366 // Wake up poll loop since it may need to make new input dispatching choices.
5367 mLooper->wake();
5368}
5369
Vishnu Nair599f1412021-06-21 10:39:58 -07005370void InputDispatcher::setFocusedApplicationLocked(
5371 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5372 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5373 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5374
5375 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5376 return; // This application is already focused. No need to wake up or change anything.
5377 }
5378
5379 // Set the new application handle.
5380 if (inputApplicationHandle != nullptr) {
5381 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5382 } else {
5383 mFocusedApplicationHandlesByDisplay.erase(displayId);
5384 }
5385
5386 // No matter what the old focused application was, stop waiting on it because it is
5387 // no longer focused.
5388 resetNoFocusedWindowTimeoutLocked();
5389}
5390
Tiger Huang721e26f2018-07-24 22:26:19 +08005391/**
5392 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5393 * the display not specified.
5394 *
5395 * We track any unreleased events for each window. If a window loses the ability to receive the
5396 * released event, we will send a cancel event to it. So when the focused display is changed, we
5397 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5398 * display. The display-specified events won't be affected.
5399 */
5400void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005401 if (DEBUG_FOCUS) {
5402 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5403 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005404 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005405 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005406
5407 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005408 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005409 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005410 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005411 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005412 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005413 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005414 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005415 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005416 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005417 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005418 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5419 }
5420 }
5421 mFocusedDisplayId = displayId;
5422
Chris Ye3c2d6f52020-08-09 10:39:48 -07005423 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005424 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005425 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005426
Vishnu Nairad321cd2020-08-20 16:40:21 -07005427 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005428 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005429 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005430 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005431 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005432 }
5433 }
5434 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005435 } // release lock
5436
5437 // Wake up poll loop since it may need to make new input dispatching choices.
5438 mLooper->wake();
5439}
5440
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005442 if (DEBUG_FOCUS) {
5443 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445
5446 bool changed;
5447 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005448 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449
5450 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5451 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005452 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 }
5454
5455 if (mDispatchEnabled && !enabled) {
5456 resetAndDropEverythingLocked("dispatcher is being disabled");
5457 }
5458
5459 mDispatchEnabled = enabled;
5460 mDispatchFrozen = frozen;
5461 changed = true;
5462 } else {
5463 changed = false;
5464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 } // release lock
5466
5467 if (changed) {
5468 // Wake up poll loop since it may need to make new input dispatching choices.
5469 mLooper->wake();
5470 }
5471}
5472
5473void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005474 if (DEBUG_FOCUS) {
5475 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477
5478 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005479 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480
5481 if (mInputFilterEnabled == enabled) {
5482 return;
5483 }
5484
5485 mInputFilterEnabled = enabled;
5486 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5487 } // release lock
5488
5489 // Wake up poll loop since there might be work to do to drop everything.
5490 mLooper->wake();
5491}
5492
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005493bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005494 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005495 bool needWake = false;
5496 {
5497 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005498 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005499 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005500 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005501 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5502 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005503 mTouchModePerDisplay.count(displayId) == 0
5504 ? "not set"
5505 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5506
Antonio Kantek15beb512022-06-13 22:35:41 +00005507 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5508 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005509 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005510 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005511 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005512 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5513 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005514 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005515 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005516 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005517 return false;
5518 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005519 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005520 mTouchModePerDisplay[displayId] = inTouchMode;
5521 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5522 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005523 needWake = enqueueInboundEventLocked(std::move(entry));
5524 } // release lock
5525
5526 if (needWake) {
5527 mLooper->wake();
5528 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005529 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005530}
5531
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005532bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005533 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5534 if (focusedToken == nullptr) {
5535 return false;
5536 }
5537 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5538 return isWindowOwnedBy(windowHandle, pid, uid);
5539}
5540
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005541bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005542 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5543 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5544 const sp<WindowInfoHandle> windowHandle =
5545 getWindowHandleLocked(connectionToken);
5546 return isWindowOwnedBy(windowHandle, pid, uid);
5547 }) != mInteractionConnectionTokens.end();
5548}
5549
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005550void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5551 if (opacity < 0 || opacity > 1) {
5552 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5553 return;
5554 }
5555
5556 std::scoped_lock lock(mLock);
5557 mMaximumObscuringOpacityForTouch = opacity;
5558}
5559
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005560std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5561InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005562 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5563 for (TouchedWindow& w : state.windows) {
5564 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005565 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005566 }
5567 }
5568 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005569 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005570}
5571
arthurhungb89ccb02020-12-30 16:19:01 +08005572bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5573 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005574 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005575 if (DEBUG_FOCUS) {
5576 ALOGD("Trivial transfer to same window.");
5577 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005578 return true;
5579 }
5580
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005582 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583
Arthur Hungabbb9d82021-09-01 14:52:30 +00005584 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005585 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005586
Arthur Hungabbb9d82021-09-01 14:52:30 +00005587 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005588 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 return false;
5590 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005591 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5592 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005593 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5594 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005595 return false;
5596 }
5597 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005598
Arthur Hungabbb9d82021-09-01 14:52:30 +00005599 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5600 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005601 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005602 return false;
5603 }
5604
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005605 if (DEBUG_FOCUS) {
5606 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005607 touchedWindow->windowHandle->getName().c_str(),
5608 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 }
5610
Arthur Hungabbb9d82021-09-01 14:52:30 +00005611 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005612 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005613 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005614 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005615 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616
Arthur Hungabbb9d82021-09-01 14:52:30 +00005617 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005618 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005619 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005620 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005621 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005622 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005623 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005624 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005625 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626
Arthur Hungabbb9d82021-09-01 14:52:30 +00005627 // Store the dragging window.
5628 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005629 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005630 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5631 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005632 return false;
5633 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005634 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005635 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005636 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 }
5638
Arthur Hungabbb9d82021-09-01 14:52:30 +00005639 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005640 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5641 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005642 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005643 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005644 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5645 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005647 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5648 newTargetFlags);
5649
5650 // Check if the wallpaper window should deliver the corresponding event.
5651 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005652 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 } // release lock
5655
5656 // Wake up poll loop since it may need to make new input dispatching choices.
5657 mLooper->wake();
5658 return true;
5659}
5660
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005661/**
5662 * Get the touched foreground window on the given display.
5663 * Return null if there are no windows touched on that display, or if more than one foreground
5664 * window is being touched.
5665 */
5666sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5667 auto stateIt = mTouchStatesByDisplay.find(displayId);
5668 if (stateIt == mTouchStatesByDisplay.end()) {
5669 ALOGI("No touch state on display %" PRId32, displayId);
5670 return nullptr;
5671 }
5672
5673 const TouchState& state = stateIt->second;
5674 sp<WindowInfoHandle> touchedForegroundWindow;
5675 // If multiple foreground windows are touched, return nullptr
5676 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005677 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005678 if (touchedForegroundWindow != nullptr) {
5679 ALOGI("Two or more foreground windows: %s and %s",
5680 touchedForegroundWindow->getName().c_str(),
5681 window.windowHandle->getName().c_str());
5682 return nullptr;
5683 }
5684 touchedForegroundWindow = window.windowHandle;
5685 }
5686 }
5687 return touchedForegroundWindow;
5688}
5689
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005690// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005691bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005692 sp<IBinder> fromToken;
5693 { // acquire lock
5694 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005695 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005696 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005697 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5698 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005699 return false;
5700 }
5701
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005702 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5703 if (from == nullptr) {
5704 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5705 return false;
5706 }
5707
5708 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005709 } // release lock
5710
5711 return transferTouchFocus(fromToken, destChannelToken);
5712}
5713
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005715 if (DEBUG_FOCUS) {
5716 ALOGD("Resetting and dropping all events (%s).", reason);
5717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718
Michael Wrightfb04fd52022-11-24 22:31:11 +00005719 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 synthesizeCancelationEventsForAllConnectionsLocked(options);
5721
5722 resetKeyRepeatLocked();
5723 releasePendingEventLocked();
5724 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005727 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005728 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729}
5730
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005731void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005732 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 dumpDispatchStateLocked(dump);
5734
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005735 std::istringstream stream(dump);
5736 std::string line;
5737
5738 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005739 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741}
5742
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005743std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005744 std::string dump;
5745
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005746 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5747 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005748
5749 std::string windowName = "None";
5750 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005751 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005752 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5753 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5754 : "token has capture without window";
5755 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005756 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005757
5758 return dump;
5759}
5760
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005761void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005762 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5763 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5764 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005765 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766
Tiger Huang721e26f2018-07-24 22:26:19 +08005767 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5768 dump += StringPrintf(INDENT "FocusedApplications:\n");
5769 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5770 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005771 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005772 const std::chrono::duration timeout =
5773 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005774 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005775 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005776 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005779 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005781
Vishnu Nairc519ff72021-01-21 08:23:08 -08005782 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005783 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005785 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005787 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005788 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5789 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 }
5791 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005792 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 }
5794
arthurhung6d4bed92021-03-17 11:59:33 +08005795 if (mDragState) {
5796 dump += StringPrintf(INDENT "DragState:\n");
5797 mDragState->dump(dump, INDENT2);
5798 }
5799
Arthur Hungb92218b2018-08-14 12:00:21 +08005800 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005801 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5802 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5803 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5804 const auto& displayInfo = it->second;
5805 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5806 displayInfo.logicalHeight);
5807 displayInfo.transform.dump(dump, "transform", INDENT4);
5808 } else {
5809 dump += INDENT2 "No DisplayInfo found!\n";
5810 }
5811
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005812 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005813 dump += INDENT2 "Windows:\n";
5814 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005815 dump += StringPrintf(INDENT3 "%zu: %s", i,
5816 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005817 }
5818 } else {
5819 dump += INDENT2 "Windows: <none>\n";
5820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 }
5822 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005823 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005824 }
5825
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005826 if (!mGlobalMonitorsByDisplay.empty()) {
5827 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5828 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005829 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005832 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 }
5834
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005835 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
5837 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005838 if (!mRecentQueue.empty()) {
5839 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005840 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005841 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005842 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005843 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
5845 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005846 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 }
5848
5849 // Dump event currently being dispatched.
5850 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005851 dump += INDENT "PendingEvent:\n";
5852 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005853 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005854 dump += StringPrintf(", age=%" PRId64 "ms\n",
5855 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005857 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858 }
5859
5860 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005861 if (!mInboundQueue.empty()) {
5862 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005863 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005864 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005865 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005866 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 }
5868 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005869 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 }
5871
Prabir Pradhancef936d2021-07-21 16:17:52 +00005872 if (!mCommandQueue.empty()) {
5873 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5874 } else {
5875 dump += INDENT "CommandQueue: <empty>\n";
5876 }
5877
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005878 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005879 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005880 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005881 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005882 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005883 connection->inputChannel->getFd().get(),
5884 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005885 connection->getWindowName().c_str(),
5886 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005887 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005889 if (!connection->outboundQueue.empty()) {
5890 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5891 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005892 dump += dumpQueue(connection->outboundQueue, currentTime);
5893
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005895 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896 }
5897
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005898 if (!connection->waitQueue.empty()) {
5899 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5900 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005901 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005903 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005905 std::string inputStateDump = streamableToString(connection->inputState);
5906 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005907 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005908 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 }
5911 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005912 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 }
5914
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005915 dump += "input_flags::remove_app_switch_drops() = ";
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07005916 dump += toString(REMOVE_APP_SWITCH_DROPS);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005917 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005919 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5920 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005922 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 }
5924
Antonio Kantek15beb512022-06-13 22:35:41 +00005925 if (!mTouchModePerDisplay.empty()) {
5926 dump += INDENT "TouchModePerDisplay:\n";
5927 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5928 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5929 std::to_string(touchMode).c_str());
5930 }
5931 } else {
5932 dump += INDENT "TouchModePerDisplay: <none>\n";
5933 }
5934
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005935 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005936 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5937 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5938 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005939 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005940 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005941 dump += INDENT "InputTracer: ";
5942 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943}
5944
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005945void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005946 const size_t numMonitors = monitors.size();
5947 for (size_t i = 0; i < numMonitors; i++) {
5948 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005949 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005950 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5951 dump += "\n";
5952 }
5953}
5954
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005955class LooperEventCallback : public LooperCallback {
5956public:
5957 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5958 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5959
5960private:
5961 std::function<int(int events)> mCallback;
5962};
5963
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005964Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005965 if (DEBUG_CHANNEL_CREATION) {
5966 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005969 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005970 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005971 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005972
5973 if (result) {
5974 return base::Error(result) << "Failed to open input channel pair with name " << name;
5975 }
5976
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005978 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005979 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005980 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005981 std::shared_ptr<Connection> connection =
5982 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5983 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005985 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5986 ALOGE("Created a new connection, but the token %p is already known", token.get());
5987 }
5988 mConnectionsByToken.emplace(token, connection);
5989
5990 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5991 this, std::placeholders::_1, token);
5992
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005993 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005994 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 } // release lock
5996
5997 // Wake the looper because some connections have changed.
5998 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005999 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000}
6001
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006002Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006003 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006004 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07006005 std::shared_ptr<InputChannel> serverChannel;
6006 std::unique_ptr<InputChannel> clientChannel;
6007 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
6008 if (result) {
6009 return base::Error(result) << "Failed to open input channel pair with name " << name;
6010 }
6011
Michael Wright3dd60e22019-03-27 22:06:44 +00006012 { // acquire lock
6013 std::scoped_lock _l(mLock);
6014
6015 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07006016 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6017 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006018 }
6019
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006020 std::shared_ptr<Connection> connection =
6021 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006022 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08006023 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006024
6025 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
6026 ALOGE("Created a new connection, but the token %p is already known", token.get());
6027 }
6028 mConnectionsByToken.emplace(token, connection);
6029 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6030 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006031
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006032 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006033
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08006034 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006035 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006036 }
Garfield Tan15601662020-09-22 15:32:38 -07006037
Michael Wright3dd60e22019-03-27 22:06:44 +00006038 // Wake the looper because some connections have changed.
6039 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006040 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006041}
6042
Garfield Tan15601662020-09-22 15:32:38 -07006043status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046
Harry Cutts33476232023-01-30 19:57:29 +00006047 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 if (status) {
6049 return status;
6050 }
6051 } // release lock
6052
6053 // Wake the poll loop because removing the connection may have changed the current
6054 // synchronization state.
6055 mLooper->wake();
6056 return OK;
6057}
6058
Garfield Tan15601662020-09-22 15:32:38 -07006059status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6060 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006061 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006062 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006063 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064 return BAD_VALUE;
6065 }
6066
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006067 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006068
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006070 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 }
6072
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08006073 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074
6075 nsecs_t currentTime = now();
6076 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6077
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006078 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 return OK;
6080}
6081
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006082void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006083 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6084 auto& [displayId, monitors] = *it;
6085 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6086 return monitor.inputChannel->getConnectionToken() == connectionToken;
6087 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006088
Michael Wright3dd60e22019-03-27 22:06:44 +00006089 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006090 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006091 } else {
6092 ++it;
6093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094 }
6095}
6096
Michael Wright3dd60e22019-03-27 22:06:44 +00006097status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006098 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006099 return pilferPointersLocked(token);
6100}
Michael Wright3dd60e22019-03-27 22:06:44 +00006101
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006102status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006103 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6104 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006105 LOG(WARNING)
6106 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006107 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006108 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006109
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006110 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006111 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006112 LOG(WARNING)
6113 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6114 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006115 return BAD_VALUE;
6116 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006117 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006118 if (deviceIds.empty()) {
6119 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006120 return BAD_VALUE;
6121 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006122
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006123 for (const DeviceId deviceId : deviceIds) {
6124 TouchState& state = *statePtr;
6125 TouchedWindow& window = *windowPtr;
6126 // Send cancel events to all the input channels we're stealing from.
6127 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6128 "input channel stole pointer stream");
6129 options.deviceId = deviceId;
6130 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006131 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6132 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006133 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006134
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006135 std::string canceledWindows;
6136 for (const TouchedWindow& w : state.windows) {
6137 const std::shared_ptr<InputChannel> channel =
6138 getInputChannelLocked(w.windowHandle->getToken());
6139 if (channel != nullptr && channel->getConnectionToken() != token) {
6140 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6141 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6142 canceledWindows += channel->getName();
6143 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006144 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006145 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6146 LOG(INFO) << "Channel " << requestingChannel->getName()
6147 << " is stealing input gesture for device " << deviceId << " from "
6148 << canceledWindows;
6149
6150 // Prevent the gesture from being sent to any other windows.
6151 // This only blocks relevant pointers to be sent to other windows
6152 window.addPilferingPointers(deviceId, pointerIds);
6153
6154 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006155 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006156 return OK;
6157}
6158
Prabir Pradhan99987712020-11-10 18:43:05 -08006159void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6160 { // acquire lock
6161 std::scoped_lock _l(mLock);
6162 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006163 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006164 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6165 windowHandle != nullptr ? windowHandle->getName().c_str()
6166 : "token without window");
6167 }
6168
Vishnu Nairc519ff72021-01-21 08:23:08 -08006169 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006170 if (focusedToken != windowToken) {
6171 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6172 enabled ? "enable" : "disable");
6173 return;
6174 }
6175
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006176 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006177 ALOGW("Ignoring request to %s Pointer Capture: "
6178 "window has %s requested pointer capture.",
6179 enabled ? "enable" : "disable", enabled ? "already" : "not");
6180 return;
6181 }
6182
Christine Franksb768bb42021-11-29 12:11:31 -08006183 if (enabled) {
6184 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6185 mIneligibleDisplaysForPointerCapture.end(),
6186 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6187 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6188 return;
6189 }
6190 }
6191
Prabir Pradhan99987712020-11-10 18:43:05 -08006192 setPointerCaptureLocked(enabled);
6193 } // release lock
6194
6195 // Wake the thread to process command entries.
6196 mLooper->wake();
6197}
6198
Christine Franksb768bb42021-11-29 12:11:31 -08006199void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6200 { // acquire lock
6201 std::scoped_lock _l(mLock);
6202 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6203 if (!isEligible) {
6204 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6205 }
6206 } // release lock
6207}
6208
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006209std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006210 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006211 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006212 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006213 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006214 }
6215 }
6216 }
6217 return std::nullopt;
6218}
6219
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006220std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6221 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006222 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006223 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006224 }
6225
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006226 for (const auto& [token, connection] : mConnectionsByToken) {
6227 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006228 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 }
6230 }
Robert Carr4e670e52018-08-15 13:26:12 -07006231
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006232 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233}
6234
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006235std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006236 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006237 if (connection == nullptr) {
6238 return "<nullptr>";
6239 }
6240 return connection->getInputChannelName();
6241}
6242
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006243void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006244 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006245 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006246}
6247
Prabir Pradhancef936d2021-07-21 16:17:52 +00006248void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006249 const std::shared_ptr<Connection>& connection,
6250 uint32_t seq, bool handled,
6251 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006253 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006254
6255 { // Start critical section
6256 auto dispatchEntryIt =
6257 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6258 [seq](auto& e) { return e->seq == seq; });
6259 if (dispatchEntryIt == connection->waitQueue.end()) {
6260 return;
6261 }
6262
6263 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6264
6265 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6266 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6267 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6268 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6269 }
6270 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6271 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6272 connection->inputChannel->getConnectionToken(),
6273 dispatchEntry.deliveryTime, consumeTime, finishTime);
6274 }
6275
6276 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6278 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006279 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006280 }
6281 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282
6283 // Dequeue the event and start the next cycle.
6284 // Because the lock might have been released, it is possible that the
6285 // contents of the wait queue to have been drained, so we need to double-check
6286 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006287 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6288 [seq](auto& e) { return e->seq == seq; });
6289 if (entryIt != connection->waitQueue.end()) {
6290 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6291 connection->waitQueue.erase(entryIt);
6292
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6294 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6295 if (!connection->responsive) {
6296 connection->responsive = isConnectionResponsive(*connection);
6297 if (connection->responsive) {
6298 // The connection was unresponsive, and now it's responsive.
6299 processConnectionResponsiveLocked(*connection);
6300 }
6301 }
6302 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006303 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6304 const InputTarget target{.inputChannel = connection->inputChannel,
6305 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006306 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006308 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006309 }
6310
6311 // Start the next dispatch cycle for this connection.
6312 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313}
6314
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6316 const sp<IBinder>& newToken) {
6317 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6318 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006319 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006320 };
6321 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322}
6323
Prabir Pradhancef936d2021-07-21 16:17:52 +00006324void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6325 auto command = [this, token, x, y]() REQUIRES(mLock) {
6326 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006327 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006328 };
6329 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006330}
6331
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006332void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006333 if (connection == nullptr) {
6334 LOG_ALWAYS_FATAL("Caller must check for nullness");
6335 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006336 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6337 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006339 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006340 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006341 return;
6342 }
6343 /**
6344 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6345 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6346 * has changed. This could cause newer entries to time out before the already dispatched
6347 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6348 * processes the events linearly. So providing information about the oldest entry seems to be
6349 * most useful.
6350 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006351 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6352 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006353 std::string reason =
6354 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006355 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006356 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006357 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006358 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006359 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006360
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006361 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6362
6363 // Stop waking up for events on this connection, it is already unresponsive
6364 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006365}
6366
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006367void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6368 std::string reason =
6369 StringPrintf("%s does not have a focused window", application->getName().c_str());
6370 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006371
Yabin Cui8eb9c552023-06-08 18:05:07 +00006372 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006373 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006374 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006375 };
6376 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006377}
6378
chaviw98318de2021-05-19 16:45:23 -05006379void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006380 const std::string& reason) {
6381 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6382 updateLastAnrStateLocked(windowLabel, reason);
6383}
6384
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006385void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6386 const std::string& reason) {
6387 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006388 updateLastAnrStateLocked(windowLabel, reason);
6389}
6390
6391void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6392 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006394 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 struct tm tm;
6396 localtime_r(&t, &tm);
6397 char timestr[64];
6398 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006399 mLastAnrState.clear();
6400 mLastAnrState += INDENT "ANR:\n";
6401 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006402 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6403 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006404 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405}
6406
Prabir Pradhancef936d2021-07-21 16:17:52 +00006407void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006408 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006409 const KeyEvent event = createKeyEvent(entry);
6410 nsecs_t delay = 0;
6411 { // release lock
6412 scoped_unlock unlock(mLock);
6413 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006414 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006415 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6416 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6417 std::to_string(t.duration().count()).c_str());
6418 }
6419 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006420
6421 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006422 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006423 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006424 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006425 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006426 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006427 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006429}
6430
Prabir Pradhancef936d2021-07-21 16:17:52 +00006431void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006432 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006433 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006434 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006435 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006436 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006437 };
6438 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006439}
6440
Prabir Pradhanedd96402022-02-15 01:46:16 -08006441void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006442 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006443 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006444 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006445 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006446 };
6447 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006448}
6449
6450/**
6451 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6452 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6453 * command entry to the command queue.
6454 */
6455void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6456 std::string reason) {
6457 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006458 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006459 if (connection.monitor) {
6460 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6461 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006462 pid = findMonitorPidByTokenLocked(connectionToken);
6463 } else {
6464 // The connection is a window
6465 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6466 reason.c_str());
6467 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6468 if (handle != nullptr) {
6469 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006470 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006471 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006472 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006473}
6474
6475/**
6476 * Tell the policy that a connection has become responsive so that it can stop ANR.
6477 */
6478void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6479 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006480 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006481 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006482 pid = findMonitorPidByTokenLocked(connectionToken);
6483 } else {
6484 // The connection is a window
6485 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6486 if (handle != nullptr) {
6487 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006488 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006489 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006490 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006491}
6492
Prabir Pradhan24047542023-11-02 17:14:59 +00006493std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006494 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006495 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006496 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006497 if (!handled) {
6498 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006499 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006500 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006501 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006503
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006504 // Get the fallback key state.
6505 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006506 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006507 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006508 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006509 connection->inputState.removeFallbackKey(originalKeyCode);
6510 }
6511
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006512 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513 // If the application handles the original key for which we previously
6514 // generated a fallback or if the window is not a foreground window,
6515 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006516 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006518 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6519 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6520 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6521 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6522 keyEntry.policyFlags);
6523 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006524 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006525 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526
6527 mLock.unlock();
6528
Prabir Pradhana41d2442023-04-20 21:30:40 +00006529 if (const auto unhandledKeyFallback =
6530 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6531 event, keyEntry.policyFlags);
6532 unhandledKeyFallback) {
6533 event = *unhandledKeyFallback;
6534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535
6536 mLock.lock();
6537
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006539 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006540 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006541 "application handled the original non-fallback key "
6542 "or is no longer a foreground target, "
6543 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006544 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006546 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006547 connection->inputState.removeFallbackKey(originalKeyCode);
6548 }
6549 } else {
6550 // If the application did not handle a non-fallback key, first check
6551 // that we are in a good state to perform unhandled key event processing
6552 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006553 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006554 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006555 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6556 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6557 "since this is not an initial down. "
6558 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6559 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6560 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006561 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006563
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006564 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6566 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6567 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6568 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6569 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006570 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006571
6572 mLock.unlock();
6573
Prabir Pradhana41d2442023-04-20 21:30:40 +00006574 bool fallback = false;
6575 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6576 event, keyEntry.policyFlags);
6577 fb) {
6578 fallback = true;
6579 event = *fb;
6580 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581
6582 mLock.lock();
6583
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006584 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006585 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006586 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006587 }
6588
6589 // Latch the fallback keycode for this key on an initial down.
6590 // The fallback keycode cannot change at any other point in the lifecycle.
6591 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006593 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006594 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006595 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006596 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006597 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006598 }
6599
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006600 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006601
6602 // Cancel the fallback key if the policy decides not to send it anymore.
6603 // We will continue to dispatch the key to the policy but we will no
6604 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006605 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6606 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006607 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6608 if (fallback) {
6609 ALOGD("Unhandled key event: Policy requested to send key %d"
6610 "as a fallback for %d, but on the DOWN it had requested "
6611 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006612 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006613 } else {
6614 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6615 "but on the DOWN it had requested to send %d. "
6616 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006617 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006618 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006619 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006620
Michael Wrightfb04fd52022-11-24 22:31:11 +00006621 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006622 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006623 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006624 synthesizeCancelationEventsForConnectionLocked(connection, options);
6625
6626 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006627 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006628 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006629 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006630 }
6631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006633 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6634 {
6635 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006636 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006637 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006638 for (const auto& [key, value] : fallbackKeys) {
6639 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006640 }
6641 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6642 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006643 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006644 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006645
6646 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006647 // Return the fallback key that we want dispatched to the channel.
6648 std::unique_ptr<KeyEntry> newEntry =
6649 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6650 event.getEventTime(), event.getDeviceId(),
6651 event.getSource(), event.getDisplayId(),
6652 keyEntry.policyFlags, keyEntry.action,
6653 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6654 *fallbackKeyCode, event.getScanCode(),
6655 event.getMetaState(), event.getRepeatCount(),
6656 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006657 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6658 ALOGD("Unhandled key event: Dispatching fallback key. "
6659 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006660 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006661 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006662 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006663 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006664 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6665 ALOGD("Unhandled key event: No fallback key.");
6666 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006667
6668 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006669 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670 }
6671 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006672 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006673}
6674
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675void InputDispatcher::traceInboundQueueLengthLocked() {
6676 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006677 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006678 }
6679}
6680
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006681void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006682 if (ATRACE_ENABLED()) {
6683 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006684 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6685 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006686 }
6687}
6688
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006689void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006690 if (ATRACE_ENABLED()) {
6691 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006692 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6693 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006694 }
6695}
6696
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006697void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006698 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006699
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006700 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006701 dumpDispatchStateLocked(dump);
6702
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006703 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006704 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006705 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006706 }
6707}
6708
6709void InputDispatcher::monitor() {
6710 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006711 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006712 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006713 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006714}
6715
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006716/**
6717 * Wake up the dispatcher and wait until it processes all events and commands.
6718 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6719 * this method can be safely called from any thread, as long as you've ensured that
6720 * the work you are interested in completing has already been queued.
6721 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006722bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006723 /**
6724 * Timeout should represent the longest possible time that a device might spend processing
6725 * events and commands.
6726 */
6727 constexpr std::chrono::duration TIMEOUT = 100ms;
6728 std::unique_lock lock(mLock);
6729 mLooper->wake();
6730 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6731 return result == std::cv_status::no_timeout;
6732}
6733
Vishnu Naire798b472020-07-23 13:52:21 -07006734/**
6735 * Sets focus to the window identified by the token. This must be called
6736 * after updating any input window handles.
6737 *
6738 * Params:
6739 * request.token - input channel token used to identify the window that should gain focus.
6740 * request.focusedToken - the token that the caller expects currently to be focused. If the
6741 * specified token does not match the currently focused window, this request will be dropped.
6742 * If the specified focused token matches the currently focused window, the call will succeed.
6743 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6744 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6745 * when requesting the focus change. This determines which request gets
6746 * precedence if there is a focus change request from another source such as pointer down.
6747 */
Vishnu Nair958da932020-08-21 17:12:37 -07006748void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6749 { // acquire lock
6750 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006751 std::optional<FocusResolver::FocusChanges> changes =
6752 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6753 if (changes) {
6754 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006755 }
6756 } // release lock
6757 // Wake up poll loop since it may need to make new input dispatching choices.
6758 mLooper->wake();
6759}
6760
Vishnu Nairc519ff72021-01-21 08:23:08 -08006761void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6762 if (changes.oldFocus) {
6763 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006764 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006765 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006766 "focus left window");
6767 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006768 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006769 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006770 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006771 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006772 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006773 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006774 }
6775
Prabir Pradhan99987712020-11-10 18:43:05 -08006776 // If a window has pointer capture, then it must have focus. We need to ensure that this
6777 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6778 // If the window loses focus before it loses pointer capture, then the window can be in a state
6779 // where it has pointer capture but not focus, violating the contract. Therefore we must
6780 // dispatch the pointer capture event before the focus event. Since focus events are added to
6781 // the front of the queue (above), we add the pointer capture event to the front of the queue
6782 // after the focus events are added. This ensures the pointer capture event ends up at the
6783 // front.
6784 disablePointerCaptureForcedLocked();
6785
Vishnu Nairc519ff72021-01-21 08:23:08 -08006786 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006787 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006788 }
6789}
Vishnu Nair958da932020-08-21 17:12:37 -07006790
Prabir Pradhan99987712020-11-10 18:43:05 -08006791void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006792 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006793 return;
6794 }
6795
6796 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6797
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006798 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006799 setPointerCaptureLocked(false);
6800 }
6801
6802 if (!mWindowTokenWithPointerCapture) {
6803 // No need to send capture changes because no window has capture.
6804 return;
6805 }
6806
6807 if (mPendingEvent != nullptr) {
6808 // Move the pending event to the front of the queue. This will give the chance
6809 // for the pending event to be dropped if it is a captured event.
6810 mInboundQueue.push_front(mPendingEvent);
6811 mPendingEvent = nullptr;
6812 }
6813
6814 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006815 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006816 mInboundQueue.push_front(std::move(entry));
6817}
6818
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006819void InputDispatcher::setPointerCaptureLocked(bool enable) {
6820 mCurrentPointerCaptureRequest.enable = enable;
6821 mCurrentPointerCaptureRequest.seq++;
6822 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006823 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006824 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006825 };
6826 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006827}
6828
Vishnu Nair599f1412021-06-21 10:39:58 -07006829void InputDispatcher::displayRemoved(int32_t displayId) {
6830 { // acquire lock
6831 std::scoped_lock _l(mLock);
6832 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006833 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006834 setFocusedApplicationLocked(displayId, nullptr);
6835 // Call focus resolver to clean up stale requests. This must be called after input windows
6836 // have been removed for the removed display.
6837 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006838 // Reset pointer capture eligibility, regardless of previous state.
6839 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006840 // Remove the associated touch mode state.
6841 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006842 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006843 } // release lock
6844
6845 // Wake up poll loop since it may need to make new input dispatching choices.
6846 mLooper->wake();
6847}
6848
Patrick Williamsd828f302023-04-28 17:52:08 -05006849void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006850 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6851 {
6852 // acquire lock
6853 std::scoped_lock _l(mLock);
6854 logDispatchStateLocked();
6855 }
6856 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6857 result.error().message().c_str());
6858 };
chaviw15fab6f2021-06-07 14:15:52 -05006859 // The listener sends the windows as a flattened array. Separate the windows by display for
6860 // more convenient parsing.
6861 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006862 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006863 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006864 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006865 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006866
6867 { // acquire lock
6868 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006869
6870 // Ensure that we have an entry created for all existing displays so that if a displayId has
6871 // no windows, we can tell that the windows were removed from the display.
6872 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6873 handlesPerDisplay[displayId];
6874 }
6875
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006876 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006877 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006878 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6879 }
6880
6881 for (const auto& [displayId, handles] : handlesPerDisplay) {
6882 setInputWindowsLocked(handles, displayId);
6883 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006884
6885 if (update.vsyncId < mWindowInfosVsyncId) {
6886 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6887 ", current update vsync id: %" PRId64,
6888 mWindowInfosVsyncId, update.vsyncId);
6889 }
6890 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006891 }
6892 // Wake up poll loop since it may need to make new input dispatching choices.
6893 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006894}
6895
Vishnu Nair062a8672021-09-03 16:07:44 -07006896bool InputDispatcher::shouldDropInput(
6897 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006898 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6899 (windowHandle->getInfo()->inputConfig.test(
6900 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006901 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006902 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6903 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006904 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006905 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006906 windowHandle->getInfo()->displayId);
6907 return true;
6908 }
6909 return false;
6910}
6911
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006912void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006913 const gui::WindowInfosUpdate& update) {
6914 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006915}
6916
Arthur Hungdfd528e2021-12-08 13:23:04 +00006917void InputDispatcher::cancelCurrentTouch() {
6918 {
6919 std::scoped_lock _l(mLock);
6920 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006921 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006922 "cancel current touch");
6923 synthesizeCancelationEventsForAllConnectionsLocked(options);
6924
6925 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006926 }
6927 // Wake up poll loop since there might be work to do.
6928 mLooper->wake();
6929}
6930
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006931void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6932 std::scoped_lock _l(mLock);
6933 mMonitorDispatchingTimeout = timeout;
6934}
6935
Arthur Hungc539dbb2022-12-08 07:45:36 +00006936void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6937 const sp<WindowInfoHandle>& oldWindowHandle,
6938 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006939 TouchState& state, int32_t deviceId,
6940 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006941 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006942 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006943 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6944 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6945 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6946 newWindowHandle->getInfo()->inputConfig.test(
6947 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6948 const sp<WindowInfoHandle> oldWallpaper =
6949 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6950 const sp<WindowInfoHandle> newWallpaper =
6951 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6952 if (oldWallpaper == newWallpaper) {
6953 return;
6954 }
6955
6956 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006957 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006958 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006959 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006960 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006961 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006962 }
6963
6964 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006965 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6966 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006967 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006968 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006969 }
6970}
6971
6972void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6973 ftl::Flags<InputTarget::Flags> newTargetFlags,
6974 const sp<WindowInfoHandle> fromWindowHandle,
6975 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006976 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006977 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006978 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6979 fromWindowHandle->getInfo()->inputConfig.test(
6980 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6981 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6982 toWindowHandle->getInfo()->inputConfig.test(
6983 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6984
6985 const sp<WindowInfoHandle> oldWallpaper =
6986 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6987 const sp<WindowInfoHandle> newWallpaper =
6988 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6989 if (oldWallpaper == newWallpaper) {
6990 return;
6991 }
6992
6993 if (oldWallpaper != nullptr) {
6994 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6995 "transferring touch focus to another window");
6996 state.removeWindowByToken(oldWallpaper->getToken());
6997 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6998 }
6999
7000 if (newWallpaper != nullptr) {
7001 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007002 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007003 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7004 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007005 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007006 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007007 std::shared_ptr<Connection> wallpaperConnection =
7008 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007009 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007010 std::shared_ptr<Connection> toConnection =
7011 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007012 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7013 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7014 wallpaperFlags);
7015 }
7016 }
7017}
7018
7019sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7020 const sp<WindowInfoHandle>& windowHandle) const {
7021 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7022 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7023 bool foundWindow = false;
7024 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7025 if (!foundWindow && otherHandle != windowHandle) {
7026 continue;
7027 }
7028 if (windowHandle == otherHandle) {
7029 foundWindow = true;
7030 continue;
7031 }
7032
7033 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7034 return otherHandle;
7035 }
7036 }
7037 return nullptr;
7038}
7039
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007040void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7041 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007042 std::scoped_lock _l(mLock);
7043
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007044 mConfig.keyRepeatTimeout = timeout.count();
7045 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007046}
7047
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007048bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7049 DeviceId deviceId, int32_t pointerId) {
7050 std::scoped_lock _l(mLock);
7051 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7052 if (touchStateIt == mTouchStatesByDisplay.end()) {
7053 return false;
7054 }
7055 for (const TouchedWindow& window : touchStateIt->second.windows) {
7056 if (window.windowHandle->getToken() == token &&
7057 (window.hasTouchingPointer(deviceId, pointerId) ||
7058 window.hasHoveringPointer(deviceId, pointerId))) {
7059 return true;
7060 }
7061 }
7062 return false;
7063}
7064
Garfield Tane84e6f92019-08-29 17:28:41 -07007065} // namespace android::inputdispatcher