blob: ec19e45cf521af95afdd45df832d43297c953712 [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
50#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000051#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070052#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010053
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#define INDENT " "
55#define INDENT2 " "
56#define INDENT3 " "
57#define INDENT4 " "
58
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080059using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070060using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080061using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000062using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070064using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050065using android::gui::FocusRequest;
66using android::gui::TouchOcclusionMode;
67using android::gui::WindowInfo;
68using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080069using android::os::InputEventInjectionResult;
70using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000071namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080072
Garfield Tane84e6f92019-08-29 17:28:41 -070073namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Prabir Pradhancef936d2021-07-21 16:17:52 +000075namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000076// Temporarily releases a held mutex for the lifetime of the instance.
77// Named to match std::scoped_lock
78class scoped_unlock {
79public:
80 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
81 ~scoped_unlock() { mMutex.lock(); }
82
83private:
84 std::mutex& mMutex;
85};
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// Default input dispatching timeout if there is no focused application or paused window
88// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080089const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
90 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
91 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Amount of time to allow for all pending events to be processed when an app switch
94// key is on the way. This is used to preempt input dispatch and drop input events
95// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080098const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100// 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 +0000101constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
102
103// Log a warning when an interception call takes longer than this to process.
104constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700106// Additional key latency in case a connection is still processing some motion events.
107// This will help with the case when a user touched a button that opens a new window,
108// and gives us the chance to dispatch the key to this new window.
109constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
110
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000112constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
113
Antonio Kantekea47acb2021-12-23 12:41:25 -0800114// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115constexpr int LOGTAG_INPUT_INTERACTION = 62000;
116constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000117constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000119const ui::Transform kIdentityTransform;
120
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000121inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122 return systemTime(SYSTEM_TIME_MONOTONIC);
123}
124
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700125bool isEmpty(const std::stringstream& ss) {
126 return ss.rdbuf()->in_avail() == 0;
127}
128
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700129inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000130 if (binder == nullptr) {
131 return "<null>";
132 }
133 return StringPrintf("%p", binder.get());
134}
135
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000136static std::string uidString(const gui::Uid& uid) {
137 return uid.toString();
138}
139
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700140Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 case AKEY_EVENT_ACTION_DOWN:
143 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 }
148}
149
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700150Result<void> validateKeyEvent(int32_t action) {
151 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152}
153
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700157 case AMOTION_EVENT_ACTION_UP: {
158 if (pointerCount != 1) {
159 return Error() << "invalid pointer count " << pointerCount;
160 }
161 return {};
162 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 case AMOTION_EVENT_ACTION_HOVER_ENTER:
165 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700166 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
167 if (pointerCount < 1) {
168 return Error() << "invalid pointer count " << pointerCount;
169 }
170 return {};
171 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800172 case AMOTION_EVENT_ACTION_CANCEL:
173 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700175 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_POINTER_DOWN:
177 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800178 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179 if (index < 0) {
180 return Error() << "invalid index " << index << " for "
181 << MotionEvent::actionToString(action);
182 }
183 if (index >= pointerCount) {
184 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
185 }
186 if (pointerCount <= 1) {
187 return Error() << "invalid pointer count " << pointerCount << " for "
188 << MotionEvent::actionToString(action);
189 }
190 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700191 }
192 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
194 if (actionButton == 0) {
195 return Error() << "action button should be nonzero for "
196 << MotionEvent::actionToString(action);
197 }
198 return {};
199 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700201 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
203}
204
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000205int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500206 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
207}
208
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700209Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
210 const PointerProperties* pointerProperties) {
211 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
212 if (!actionCheck.ok()) {
213 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
215 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700216 return Error() << "Motion event has invalid pointer count " << pointerCount
217 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800219 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 for (size_t i = 0; i < pointerCount; i++) {
221 int32_t id = pointerProperties[i].id;
222 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700223 return Error() << "Motion event has invalid pointer id " << id
224 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800226 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700227 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800229 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700231 return {};
232}
233
234Result<void> validateInputEvent(const InputEvent& event) {
235 switch (event.getType()) {
236 case InputEventType::KEY: {
237 const KeyEvent& key = static_cast<const KeyEvent&>(event);
238 const int32_t action = key.getAction();
239 return validateKeyEvent(action);
240 }
241 case InputEventType::MOTION: {
242 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
243 const int32_t action = motion.getAction();
244 const size_t pointerCount = motion.getPointerCount();
245 const PointerProperties* pointerProperties = motion.getPointerProperties();
246 const int32_t actionButton = motion.getActionButton();
247 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
248 }
249 default: {
250 return {};
251 }
252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253}
254
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000255std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000257 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 }
259
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000260 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 bool first = true;
262 Region::const_iterator cur = region.begin();
263 Region::const_iterator const tail = region.end();
264 while (cur != tail) {
265 if (first) {
266 first = false;
267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 cur++;
272 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000273 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274}
275
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000276std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
277 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500278 constexpr size_t maxEntries = 50; // max events to print
279 constexpr size_t skipBegin = maxEntries / 2;
280 const size_t skipEnd = queue.size() - maxEntries / 2;
281 // skip from maxEntries / 2 ... size() - maxEntries/2
282 // only print from 0 .. skipBegin and then from skipEnd .. size()
283
284 std::string dump;
285 for (size_t i = 0; i < queue.size(); i++) {
286 const DispatchEntry& entry = *queue[i];
287 if (i >= skipBegin && i < skipEnd) {
288 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
289 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
290 continue;
291 }
292 dump.append(INDENT4);
293 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800294 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
295 "ms",
296 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500297 ns2ms(currentTime - entry.eventEntry->eventTime));
298 if (entry.deliveryTime != 0) {
299 // This entry was delivered, so add information on how long we've been waiting
300 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
301 }
302 dump.append("\n");
303 }
304 return dump;
305}
306
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700307/**
308 * Find the entry in std::unordered_map by key, and return it.
309 * If the entry is not found, return a default constructed entry.
310 *
311 * Useful when the entries are vectors, since an empty vector will be returned
312 * if the entry is not found.
313 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
314 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000316V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700317 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700318 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800319}
320
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000321bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700322 if (first == second) {
323 return true;
324 }
325
326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329
330 return first->getToken() == second->getToken();
331}
332
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000333bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000334 if (first == nullptr || second == nullptr) {
335 return false;
336 }
337 return first->applicationInfo.token != nullptr &&
338 first->applicationInfo.token == second->applicationInfo.token;
339}
340
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800341template <typename T>
342size_t firstMarkedBit(T set) {
343 // TODO: replace with std::countr_zero from <bit> when that's available
344 LOG_ALWAYS_FATAL_IF(set.none());
345 size_t i = 0;
346 while (!set.test(i)) {
347 i++;
348 }
349 return i;
350}
351
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800352std::unique_ptr<DispatchEntry> createDispatchEntry(
353 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
354 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 if (inputTarget.useDefaultPointerTransform()) {
356 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700358 inputTarget.displayTransform,
359 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360 }
361
362 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700365 std::vector<PointerCoords> pointerCoords;
366 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 // Use the first pointer information to normalize all other pointers. This could be any pointer
369 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // uses the transform for the normalized pointer.
371 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800372 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700373 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374
375 // Iterate through all pointers in the event to normalize against the first.
376 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
377 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
378 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 // First, apply the current pointer's transform to update the coordinates into
383 // window space.
384 pointerCoords[pointerIndex].transform(currTransform);
385 // Next, apply the inverse transform of the normalized coordinates so the
386 // current coordinates are transformed into the normalized coordinate space.
387 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388 }
389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700390 std::unique_ptr<MotionEntry> combinedMotionEntry =
391 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
392 motionEntry.deviceId, motionEntry.source,
393 motionEntry.displayId, motionEntry.policyFlags,
394 motionEntry.action, motionEntry.actionButton,
395 motionEntry.flags, motionEntry.metaState,
396 motionEntry.buttonState, motionEntry.classification,
397 motionEntry.edgeFlags, motionEntry.xPrecision,
398 motionEntry.yPrecision, motionEntry.xCursorPosition,
399 motionEntry.yCursorPosition, motionEntry.downTime,
400 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000401 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000402
403 if (motionEntry.injectionState) {
404 combinedMotionEntry->injectionState = motionEntry.injectionState;
405 combinedMotionEntry->injectionState->refCount += 1;
406 }
407
408 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700409 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700410 firstPointerTransform, inputTarget.displayTransform,
411 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412 return dispatchEntry;
413}
414
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000415status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
416 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700417 std::unique_ptr<InputChannel> uniqueServerChannel;
418 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
419
420 serverChannel = std::move(uniqueServerChannel);
421 return result;
422}
423
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000425bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500426 if (lhs == nullptr && rhs == nullptr) {
427 return true;
428 }
429 if (lhs == nullptr || rhs == nullptr) {
430 return false;
431 }
432 return *lhs == *rhs;
433}
434
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000436 KeyEvent event;
437 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
438 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
439 entry.repeatCount, entry.downTime, entry.eventTime);
440 return event;
441}
442
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000443bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000444 // Do not keep track of gesture monitors. They receive every event and would disproportionately
445 // affect the statistics.
446 if (connection.monitor) {
447 return false;
448 }
449 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
450 if (!connection.responsive) {
451 return false;
452 }
453 return true;
454}
455
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000456bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000457 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
458 const int32_t& inputEventId = eventEntry.id;
459 if (inputEventId != dispatchEntry.resolvedEventId) {
460 // Event was transmuted
461 return false;
462 }
463 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
464 return false;
465 }
466 // Only track latency for events that originated from hardware
467 if (eventEntry.isSynthesized()) {
468 return false;
469 }
470 const EventEntry::Type& inputEventEntryType = eventEntry.type;
471 if (inputEventEntryType == EventEntry::Type::KEY) {
472 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
473 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
474 return false;
475 }
476 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
477 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
478 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
479 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
480 return false;
481 }
482 } else {
483 // Not a key or a motion
484 return false;
485 }
486 if (!shouldReportMetricsForConnection(connection)) {
487 return false;
488 }
489 return true;
490}
491
Prabir Pradhancef936d2021-07-21 16:17:52 +0000492/**
493 * Connection is responsive if it has no events in the waitQueue that are older than the
494 * current time.
495 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000496bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000497 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000498 for (const auto& dispatchEntry : connection.waitQueue) {
499 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000500 return false;
501 }
502 }
503 return true;
504}
505
Antonio Kantekf16f2832021-09-28 04:39:20 +0000506// Returns true if the event type passed as argument represents a user activity.
507bool isUserActivityEvent(const EventEntry& eventEntry) {
508 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000509 case EventEntry::Type::CONFIGURATION_CHANGED:
510 case EventEntry::Type::DEVICE_RESET:
511 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 case EventEntry::Type::FOCUS:
513 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000515 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000516 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 case EventEntry::Type::KEY:
518 case EventEntry::Type::MOTION:
519 return true;
520 }
521}
522
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800523// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000524bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000525 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800526 const auto inputConfig = windowInfo.inputConfig;
527 if (windowInfo.displayId != displayId ||
528 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800529 return false;
530 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700531 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800532 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800533 return false;
534 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000535
536 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
537 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
538 // the window. Points on the right and bottom edges should not be inside the window, so we need
539 // to be careful about performing a hit test when the display is rotated, since the "right" and
540 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
541 // logical display in which WM determined the bounds. Perform the hit test in the logical
542 // display space to ensure these edges are considered correctly in all orientations.
543 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
544 const auto p = displayTransform.transform(x, y);
545 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800546 return false;
547 }
548 return true;
549}
550
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
552 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000553 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700554}
555
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800556// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000557// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
558// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
559// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800560// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000561bool canReceiveForegroundTouches(const WindowInfo& info) {
562 // A non-touchable window can still receive touch events (e.g. in the case of
563 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
564 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
565}
566
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000567bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700568 if (windowHandle == nullptr) {
569 return false;
570 }
571 const WindowInfo* windowInfo = windowHandle->getInfo();
572 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
573 return true;
574 }
575 return false;
576}
577
Prabir Pradhan5735a322022-04-11 17:23:34 +0000578// Checks targeted injection using the window's owner's uid.
579// Returns an empty string if an entry can be sent to the given window, or an error message if the
580// entry is a targeted injection whose uid target doesn't match the window owner.
581std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
582 const EventEntry& entry) {
583 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
584 // The event was not injected, or the injected event does not target a window.
585 return {};
586 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000587 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000589 return StringPrintf("No valid window target for injection into uid %s.",
590 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000591 }
592 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000593 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
594 "owned by uid %s.",
595 uid.toString().c_str(), window->getName().c_str(),
596 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000597 }
598 return {};
599}
600
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000601std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
603 // Always dispatch mouse events to cursor position.
604 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000605 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700606 }
607
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700608 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000609 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
610 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700611}
612
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700613std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
614 if (eventEntry.type == EventEntry::Type::KEY) {
615 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
616 return keyEntry.downTime;
617 } else if (eventEntry.type == EventEntry::Type::MOTION) {
618 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
619 return motionEntry.downTime;
620 }
621 return std::nullopt;
622}
623
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000624/**
625 * Compare the old touch state to the new touch state, and generate the corresponding touched
626 * windows (== input targets).
627 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
628 * If the pointer just entered the new window, produce HOVER_ENTER.
629 * For pointers remaining in the window, produce HOVER_MOVE.
630 */
631std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
632 const TouchState& newTouchState,
633 const MotionEntry& entry) {
634 std::vector<TouchedWindow> out;
635 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
636 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
637 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
638 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
639 // Not a hover event - don't need to do anything
640 return out;
641 }
642
643 // We should consider all hovering pointers here. But for now, just use the first one
644 const int32_t pointerId = entry.pointerProperties[0].id;
645
646 std::set<sp<WindowInfoHandle>> oldWindows;
647 if (oldState != nullptr) {
648 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
649 }
650
651 std::set<sp<WindowInfoHandle>> newWindows =
652 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
653
654 // If the pointer is no longer in the new window set, send HOVER_EXIT.
655 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
656 if (newWindows.find(oldWindow) == newWindows.end()) {
657 TouchedWindow touchedWindow;
658 touchedWindow.windowHandle = oldWindow;
659 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 out.push_back(touchedWindow);
661 }
662 }
663
664 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
665 TouchedWindow touchedWindow;
666 touchedWindow.windowHandle = newWindow;
667 if (oldWindows.find(newWindow) == oldWindows.end()) {
668 // Any windows that have this pointer now, and didn't have it before, should get
669 // HOVER_ENTER
670 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
671 } else {
672 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700674 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000675 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
676 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700677 // The Accessibility injected touch exploration event stream
678 // has known inconsistencies, so log ERROR instead of
679 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700680 severity = android::base::LogSeverity::ERROR;
681 }
682 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700683 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
685 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700686 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000687 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
688 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
689 }
690 out.push_back(touchedWindow);
691 }
692 return out;
693}
694
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800695template <typename T>
696std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
697 left.insert(left.end(), right.begin(), right.end());
698 return left;
699}
700
Harry Cuttsb166c002023-05-09 13:06:05 +0000701// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
702// both.
703void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
704 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
705 if (!window.windowHandle->getInfo()->inputConfig.test(
706 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
707 // In addition to TouchState, erase this window from the input targets! We don't have a
708 // good way to do this today except by adding a nested loop.
709 // TODO(b/282025641): simplify this code once InputTargets are being identified
710 // separately from TouchedWindows.
711 std::erase_if(targets, [&](const InputTarget& target) {
712 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
713 });
714 return true;
715 }
716 return false;
717 });
718}
719
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700720/**
721 * In general, touch should be always split between windows. Some exceptions:
722 * 1. Don't split touch if all of the below is true:
723 * (a) we have an active pointer down *and*
724 * (b) a new pointer is going down that's from the same device *and*
725 * (c) the window that's receiving the current pointer does not support split touch.
726 * 2. Don't split mouse events
727 */
728bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
729 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
730 // We should never split mouse events
731 return false;
732 }
733 for (const TouchedWindow& touchedWindow : touchState.windows) {
734 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
735 // Spy windows should not affect whether or not touch is split.
736 continue;
737 }
738 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
739 continue;
740 }
741 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
742 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
743 // Wallpaper window should not affect whether or not touch is split
744 continue;
745 }
746
747 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
748 return false;
749 }
750 }
751 return true;
752}
753
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000754} // namespace
755
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756// --- InputDispatcher ---
757
Prabir Pradhana41d2442023-04-20 21:30:40 +0000758InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800759 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
760
Prabir Pradhana41d2442023-04-20 21:30:40 +0000761InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800762 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700763 : mPolicy(policy),
764 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700765 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800766 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700768 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800770 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700771 mDispatchEnabled(false),
772 mDispatchFrozen(false),
773 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100774 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000775 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800776 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800777 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000778 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000779 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700780 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800781 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700783 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700784#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700785 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700786#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700787 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788}
789
790InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792
Prabir Pradhancef936d2021-07-21 16:17:52 +0000793 resetKeyRepeatLocked();
794 releasePendingEventLocked();
795 drainInboundQueueLocked();
796 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000798 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700799 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000800 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802}
803
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700805 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700806 return ALREADY_EXISTS;
807 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700808 mThread = std::make_unique<InputThread>(
809 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
810 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700811}
812
813status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700814 if (mThread && mThread->isCallingThread()) {
815 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700816 return INVALID_OPERATION;
817 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700818 mThread.reset();
819 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700820}
821
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700823 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800825 std::scoped_lock _l(mLock);
826 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827
828 // Run a dispatch loop if there are no pending commands.
829 // The dispatch loop might enqueue commands to run afterwards.
830 if (!haveCommandsLocked()) {
831 dispatchOnceInnerLocked(&nextWakeupTime);
832 }
833
834 // Run all pending commands if there are any.
835 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000836 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700837 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800839
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 // If we are still waiting for ack on some events,
841 // we might have to wake up earlier to check if an app is anr'ing.
842 const nsecs_t nextAnrCheck = processAnrsLocked();
843 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
844
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800845 // We are about to enter an infinitely long sleep, because we have no commands or
846 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700847 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800848 mDispatcherEnteredIdle.notify_all();
849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 } // release lock
851
852 // Wait for callback or timeout or wake. (make sure we round up, not down)
853 nsecs_t currentTime = now();
854 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
855 mLooper->pollOnce(timeoutMillis);
856}
857
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500859 * Raise ANR if there is no focused window.
860 * Before the ANR is raised, do a final state check:
861 * 1. The currently focused application must be the same one we are waiting for.
862 * 2. Ensure we still don't have a focused window.
863 */
864void InputDispatcher::processNoFocusedWindowAnrLocked() {
865 // Check if the application that we are waiting for is still focused.
866 std::shared_ptr<InputApplicationHandle> focusedApplication =
867 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
868 if (focusedApplication == nullptr ||
869 focusedApplication->getApplicationToken() !=
870 mAwaitedFocusedApplication->getApplicationToken()) {
871 // Unexpected because we should have reset the ANR timer when focused application changed
872 ALOGE("Waited for a focused window, but focused application has already changed to %s",
873 focusedApplication->getName().c_str());
874 return; // The focused application has changed.
875 }
876
chaviw98318de2021-05-19 16:45:23 -0500877 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500878 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
879 if (focusedWindowHandle != nullptr) {
880 return; // We now have a focused window. No need for ANR.
881 }
882 onAnrLocked(mAwaitedFocusedApplication);
883}
884
885/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 * Check if any of the connections' wait queues have events that are too old.
887 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
888 * Return the time at which we should wake up next.
889 */
890nsecs_t InputDispatcher::processAnrsLocked() {
891 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700892 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
894 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
895 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500896 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700897 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500898 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700899 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700900 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500901 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700902 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
903 }
904 }
905
906 // Check if any connection ANRs are due
907 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
908 if (currentTime < nextAnrCheck) { // most likely scenario
909 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
910 }
911
912 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700913 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 if (connection == nullptr) {
915 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
916 return nextAnrCheck;
917 }
918 connection->responsive = false;
919 // Stop waking up for this unresponsive connection
920 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000921 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700922 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923}
924
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800925std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700926 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800927 if (connection->monitor) {
928 return mMonitorDispatchingTimeout;
929 }
930 const sp<WindowInfoHandle> window =
931 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500933 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500935 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936}
937
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
939 nsecs_t currentTime = now();
940
Jeff Browndc5992e2014-04-11 01:27:26 -0700941 // Reset the key repeat timer whenever normal dispatch is suspended while the
942 // device is in a non-interactive state. This is to ensure that we abort a key
943 // repeat if the device is just coming out of sleep.
944 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 resetKeyRepeatLocked();
946 }
947
948 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
949 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100950 if (DEBUG_FOCUS) {
951 ALOGD("Dispatch frozen. Waiting some more.");
952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 return;
954 }
955
956 // Optimize latency of app switches.
957 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
958 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
959 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
960 if (mAppSwitchDueTime < *nextWakeupTime) {
961 *nextWakeupTime = mAppSwitchDueTime;
962 }
963
964 // Ready to start a new event.
965 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 if (isAppSwitchDue) {
969 // The inbound queue is empty so the app switch key we were waiting
970 // for will never arrive. Stop waiting for it.
971 resetPendingAppSwitchLocked(false);
972 isAppSwitchDue = false;
973 }
974
975 // Synthesize a key repeat if appropriate.
976 if (mKeyRepeatState.lastKeyEntry) {
977 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
978 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
979 } else {
980 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
981 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
982 }
983 }
984 }
985
986 // Nothing to do if there is no pending event.
987 if (!mPendingEvent) {
988 return;
989 }
990 } else {
991 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700992 mPendingEvent = mInboundQueue.front();
993 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 traceInboundQueueLengthLocked();
995 }
996
997 // Poke user activity for this event.
998 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 // Now we have an event to dispatch.
1004 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013
1014 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001019 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 const ConfigurationChangedEntry& typedEntry =
1021 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 break;
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001027 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 const DeviceResetEntry& typedEntry =
1029 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 break;
1033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001036 std::shared_ptr<FocusEntry> typedEntry =
1037 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001038 dispatchFocusLocked(currentTime, typedEntry);
1039 done = true;
1040 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1041 break;
1042 }
1043
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001044 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1045 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1046 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1047 done = true;
1048 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1049 break;
1050 }
1051
Prabir Pradhan99987712020-11-10 18:43:05 -08001052 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1053 const auto typedEntry =
1054 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1055 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1056 done = true;
1057 break;
1058 }
1059
arthurhungb89ccb02020-12-30 16:19:01 +08001060 case EventEntry::Type::DRAG: {
1061 std::shared_ptr<DragEntry> typedEntry =
1062 std::static_pointer_cast<DragEntry>(mPendingEvent);
1063 dispatchDragLocked(currentTime, typedEntry);
1064 done = true;
1065 break;
1066 }
1067
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 resetPendingAppSwitchLocked(true);
1073 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 } else if (dropReason == DropReason::NOT_DROPPED) {
1075 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 }
1077 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001078 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1082 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 break;
1086 }
1087
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001088 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 std::shared_ptr<MotionEntry> motionEntry =
1090 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1092 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001094 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1098 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 }
Chris Yef59a2f42020-10-16 12:55:26 -07001103
1104 case EventEntry::Type::SENSOR: {
1105 std::shared_ptr<SensorEntry> sensorEntry =
1106 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1107 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1108 dropReason = DropReason::APP_SWITCH;
1109 }
1110 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1111 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1112 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1113 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1114 dropReason = DropReason::STALE;
1115 }
1116 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1117 done = true;
1118 break;
1119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
1121
1122 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
Michael Wright3a981722015-06-10 15:26:13 +01001126 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127
1128 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001129 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131}
1132
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001133bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1134 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1135}
1136
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001137/**
1138 * Return true if the events preceding this incoming motion event should be dropped
1139 * Return false otherwise (the default behaviour)
1140 */
1141bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001142 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001143 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001144
1145 // Optimize case where the current application is unresponsive and the user
1146 // decides to touch a window in a different application.
1147 // If the application takes too long to catch up then we drop all events preceding
1148 // the touch into the other window.
1149 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001150 const int32_t displayId = motionEntry.displayId;
1151 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001152 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001153
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001154 sp<WindowInfoHandle> touchedWindowHandle =
1155 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001156 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001157 touchedWindowHandle->getApplicationToken() !=
1158 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001159 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001160 ALOGI("Pruning input queue because user touched a different application while waiting "
1161 "for %s",
1162 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001163 return true;
1164 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001165
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001166 // Alternatively, maybe there's a spy window that could handle this event.
1167 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1168 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1169 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001170 const std::shared_ptr<Connection> connection =
1171 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001172 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001173 // This spy window could take more input. Drop all events preceding this
1174 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001176 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001177 mAwaitedFocusedApplication->getName().c_str());
1178 return true;
1179 }
1180 }
1181 }
1182
1183 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1184 // yet been processed by some connections, the dispatcher will wait for these motion
1185 // events to be processed before dispatching the key event. This is because these motion events
1186 // may cause a new window to be launched, which the user might expect to receive focus.
1187 // To prevent waiting forever for such events, just send the key to the currently focused window
1188 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1189 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1190 "just send the pending key event to the focused window.");
1191 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001192 }
1193 return false;
1194}
1195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001197 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 mInboundQueue.push_back(std::move(newEntry));
1199 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 traceInboundQueueLengthLocked();
1201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001203 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001204 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1205 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 // Optimize app switch latency.
1207 // If the application takes too long to catch up then we drop all events preceding
1208 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001215 if (DEBUG_APP_SWITCH) {
1216 ALOGD("App switch is pending!");
1217 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 mAppSwitchSawKeyDown = false;
1220 needWake = true;
1221 }
1222 }
1223 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001224
1225 // If a new up event comes in, and the pending event with same key code has been asked
1226 // to try again later because of the policy. We have to reset the intercept key wake up
1227 // time for it may have been handled in the policy and could be dropped.
1228 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1229 mPendingEvent->type == EventEntry::Type::KEY) {
1230 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1231 if (pendingKey.keyCode == keyEntry.keyCode &&
1232 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001233 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1234 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001235 pendingKey.interceptKeyWakeupTime = 0;
1236 needWake = true;
1237 }
1238 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 break;
1240 }
1241
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001242 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001243 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1244 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1246 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001251 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001252 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1253 break;
1254 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001255 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001256 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001257 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001258 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001259 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1260 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 // nothing to do
1262 break;
1263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265
1266 return needWake;
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001270 // Do not store sensor event in recent queue to avoid flooding the queue.
1271 if (entry->type != EventEntry::Type::SENSOR) {
1272 mRecentQueue.push_back(entry);
1273 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001274 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001275 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277}
1278
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001279sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1280 bool isStylus,
1281 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001283 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001284 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001285 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001286 continue;
1287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001289 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001290 if (!info.isSpy() &&
1291 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001292 return windowHandle;
1293 }
1294 }
1295 return nullptr;
1296}
1297
1298std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001299 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001300 if (touchedWindow == nullptr) {
1301 return {};
1302 }
1303 // Traverse windows from front to back until we encounter the touched window.
1304 std::vector<InputTarget> outsideTargets;
1305 const auto& windowHandles = getWindowHandlesLocked(displayId);
1306 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1307 if (windowHandle == touchedWindow) {
1308 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1309 // below the touched window will not get ACTION_OUTSIDE event.
1310 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001311 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001312
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001313 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001314 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001315 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1316 pointerIds.set(pointerId);
1317 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1318 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001321 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322}
1323
Prabir Pradhand65552b2021-10-07 11:23:50 -07001324std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001325 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001326 // Traverse windows from front to back and gather the touched spy windows.
1327 std::vector<sp<WindowInfoHandle>> spyWindows;
1328 const auto& windowHandles = getWindowHandlesLocked(displayId);
1329 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1330 const WindowInfo& info = *windowHandle->getInfo();
1331
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001332 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001333 continue;
1334 }
1335 if (!info.isSpy()) {
1336 // The first touched non-spy window was found, so return the spy windows touched so far.
1337 return spyWindows;
1338 }
1339 spyWindows.push_back(windowHandle);
1340 }
1341 return spyWindows;
1342}
1343
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001344void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 const char* reason;
1346 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001347 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001348 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001349 ALOGD("Dropped event because policy consumed it.");
1350 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001351 reason = "inbound event was dropped because the policy consumed it";
1352 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001353 case DropReason::DISABLED:
1354 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001355 ALOGI("Dropped event because input dispatch is disabled.");
1356 }
1357 reason = "inbound event was dropped because input dispatch is disabled";
1358 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001359 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360 ALOGI("Dropped event because of pending overdue app switch.");
1361 reason = "inbound event was dropped because of pending overdue app switch";
1362 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001363 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001364 ALOGI("Dropped event because the current application is not responding and the user "
1365 "has started interacting with a different application.");
1366 reason = "inbound event was dropped because the current application is not responding "
1367 "and the user has started interacting with a different application";
1368 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001369 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 ALOGI("Dropped event because it is stale.");
1371 reason = "inbound event was dropped because it is stale";
1372 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001373 case DropReason::NO_POINTER_CAPTURE:
1374 ALOGI("Dropped event because there is no window with Pointer Capture.");
1375 reason = "inbound event was dropped because there is no window with Pointer Capture";
1376 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001377 case DropReason::NOT_DROPPED: {
1378 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001379 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 }
1382
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001383 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001384 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001385 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001389 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001390 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1391 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001392 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393 synthesizeCancelationEventsForAllConnectionsLocked(options);
1394 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001395 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1396 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 synthesizeCancelationEventsForAllConnectionsLocked(options);
1398 }
1399 break;
1400 }
Chris Yef59a2f42020-10-16 12:55:26 -07001401 case EventEntry::Type::SENSOR: {
1402 break;
1403 }
arthurhungb89ccb02020-12-30 16:19:01 +08001404 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1405 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001406 break;
1407 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001408 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001409 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001410 case EventEntry::Type::CONFIGURATION_CHANGED:
1411 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001412 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001413 break;
1414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416}
1417
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001418static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1420 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421}
1422
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001423bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1424 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1425 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1426 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427}
1428
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001429bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001430 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431}
1432
1433void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001434 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001436 if (DEBUG_APP_SWITCH) {
1437 if (handled) {
1438 ALOGD("App switch has arrived.");
1439 } else {
1440 ALOGD("App switch was abandoned.");
1441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443}
1444
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001446 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447}
1448
Prabir Pradhancef936d2021-07-21 16:17:52 +00001449bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001450 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return false;
1452 }
1453
1454 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001455 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001456 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001457 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1458 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001459 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 return true;
1461}
1462
Prabir Pradhancef936d2021-07-21 16:17:52 +00001463void InputDispatcher::postCommandLocked(Command&& command) {
1464 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465}
1466
1467void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001469 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001470 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 releaseInboundEventLocked(entry);
1472 }
1473 traceInboundQueueLengthLocked();
1474}
1475
1476void InputDispatcher::releasePendingEventLocked() {
1477 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001479 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481}
1482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001486 if (DEBUG_DISPATCH_CYCLE) {
1487 ALOGD("Injected inbound event was dropped.");
1488 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001489 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 }
1491 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001492 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 }
1494 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495}
1496
1497void InputDispatcher::resetKeyRepeatLocked() {
1498 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001499 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 }
1501}
1502
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001503std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1504 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505
Michael Wright2e732952014-09-24 13:26:59 -07001506 uint32_t policyFlags = entry->policyFlags &
1507 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001509 std::shared_ptr<KeyEntry> newEntry =
1510 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1511 entry->source, entry->displayId, policyFlags, entry->action,
1512 entry->flags, entry->keyCode, entry->scanCode,
1513 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001515 newEntry->syntheticRepeat = true;
1516 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001521bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001523 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1524 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526
1527 // Reset key repeating in case a keyboard device was added or removed or something.
1528 resetKeyRepeatLocked();
1529
1530 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001531 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1532 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001533 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001534 };
1535 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 return true;
1537}
1538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001539bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1540 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001541 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1542 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1543 entry.deviceId);
1544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545
liushenxiang42232912021-05-21 20:24:09 +08001546 // Reset key repeating in case a keyboard device was disabled or enabled.
1547 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1548 resetKeyRepeatLocked();
1549 }
1550
Michael Wrightfb04fd52022-11-24 22:31:11 +00001551 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001552 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001554
1555 // Remove all active pointers from this device
1556 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1557 touchState.removeAllPointersForDevice(entry.deviceId);
1558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 return true;
1560}
1561
Vishnu Nairad321cd2020-08-20 16:40:21 -07001562void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001563 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001564 if (mPendingEvent != nullptr) {
1565 // Move the pending event to the front of the queue. This will give the chance
1566 // for the pending event to get dispatched to the newly focused window
1567 mInboundQueue.push_front(mPendingEvent);
1568 mPendingEvent = nullptr;
1569 }
1570
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001571 std::unique_ptr<FocusEntry> focusEntry =
1572 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1573 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001574
1575 // This event should go to the front of the queue, but behind all other focus events
1576 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001578 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001579 [](const std::shared_ptr<EventEntry>& event) {
1580 return event->type == EventEntry::Type::FOCUS;
1581 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001582
1583 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001584 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001585}
1586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001588 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001589 if (channel == nullptr) {
1590 return; // Window has gone away
1591 }
1592 InputTarget target;
1593 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001594 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001595 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001596 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1597 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001598 std::string reason = std::string("reason=").append(entry->reason);
1599 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001600 dispatchEventLocked(currentTime, entry, {target});
1601}
1602
Prabir Pradhan99987712020-11-10 18:43:05 -08001603void InputDispatcher::dispatchPointerCaptureChangedLocked(
1604 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1605 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001606 dropReason = DropReason::NOT_DROPPED;
1607
Prabir Pradhan99987712020-11-10 18:43:05 -08001608 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001609 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001610
1611 if (entry->pointerCaptureRequest.enable) {
1612 // Enable Pointer Capture.
1613 if (haveWindowWithPointerCapture &&
1614 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001615 // This can happen if pointer capture is disabled and re-enabled before we notify the
1616 // app of the state change, so there is no need to notify the app.
1617 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1618 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001619 }
1620 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001621 // This can happen if a window requests capture and immediately releases capture.
1622 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001623 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001624 return;
1625 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001626 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1627 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1628 return;
1629 }
1630
Vishnu Nairc519ff72021-01-21 08:23:08 -08001631 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001632 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1633 mWindowTokenWithPointerCapture = token;
1634 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001635 // Disable Pointer Capture.
1636 // We do not check if the sequence number matches for requests to disable Pointer Capture
1637 // for two reasons:
1638 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1639 // to disable capture with the same sequence number: one generated by
1640 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1641 // Capture being disabled in InputReader.
1642 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1643 // actual Pointer Capture state that affects events being generated by input devices is
1644 // in InputReader.
1645 if (!haveWindowWithPointerCapture) {
1646 // Pointer capture was already forcefully disabled because of focus change.
1647 dropReason = DropReason::NOT_DROPPED;
1648 return;
1649 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001650 token = mWindowTokenWithPointerCapture;
1651 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001652 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001653 setPointerCaptureLocked(false);
1654 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001655 }
1656
1657 auto channel = getInputChannelLocked(token);
1658 if (channel == nullptr) {
1659 // Window has gone away, clean up Pointer Capture state.
1660 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001661 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001662 setPointerCaptureLocked(false);
1663 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 return;
1665 }
1666 InputTarget target;
1667 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001668 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001669 entry->dispatchInProgress = true;
1670 dispatchEventLocked(currentTime, entry, {target});
1671
1672 dropReason = DropReason::NOT_DROPPED;
1673}
1674
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001675void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1676 const std::shared_ptr<TouchModeEntry>& entry) {
1677 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001678 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001679 if (windowHandles.empty()) {
1680 return;
1681 }
1682 const std::vector<InputTarget> inputTargets =
1683 getInputTargetsFromWindowHandlesLocked(windowHandles);
1684 if (inputTargets.empty()) {
1685 return;
1686 }
1687 entry->dispatchInProgress = true;
1688 dispatchEventLocked(currentTime, entry, inputTargets);
1689}
1690
1691std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1692 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1693 std::vector<InputTarget> inputTargets;
1694 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001695 const sp<IBinder>& token = handle->getToken();
1696 if (token == nullptr) {
1697 continue;
1698 }
1699 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1700 if (channel == nullptr) {
1701 continue; // Window has gone away
1702 }
1703 InputTarget target;
1704 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001705 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001706 inputTargets.push_back(target);
1707 }
1708 return inputTargets;
1709}
1710
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001711bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001714 if (!entry->dispatchInProgress) {
1715 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1716 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1717 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1718 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001719 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 // We have seen two identical key downs in a row which indicates that the device
1721 // driver is automatically generating key repeats itself. We take note of the
1722 // repeat here, but we disable our own next key repeat timer since it is clear that
1723 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001724 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1725 // Make sure we don't get key down from a different device. If a different
1726 // device Id has same key pressed down, the new device Id will replace the
1727 // current one to hold the key repeat with repeat count reset.
1728 // In the future when got a KEY_UP on the device id, drop it and do not
1729 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1731 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001732 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 } else {
1734 // Not a repeat. Save key down state in case we do see a repeat later.
1735 resetKeyRepeatLocked();
1736 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1737 }
1738 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001739 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1740 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001741 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001742 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001743 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1744 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001745 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 resetKeyRepeatLocked();
1747 }
1748
1749 if (entry->repeatCount == 1) {
1750 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1751 } else {
1752 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1753 }
1754
1755 entry->dispatchInProgress = true;
1756
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759
1760 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001761 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 if (currentTime < entry->interceptKeyWakeupTime) {
1763 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1764 *nextWakeupTime = entry->interceptKeyWakeupTime;
1765 }
1766 return false; // wait until next wakeup
1767 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001768 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 entry->interceptKeyWakeupTime = 0;
1770 }
1771
1772 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001773 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001775 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001776 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001777
1778 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1779 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1780 };
1781 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001782 // Poke user activity for keys not passed to user
1783 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 return false; // wait for the command to run
1785 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001786 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001788 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001789 if (*dropReason == DropReason::NOT_DROPPED) {
1790 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
1792 }
1793
1794 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001795 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001796 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001797 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1798 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001799 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001800 // Poke user activity for undispatched keys
1801 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 return true;
1803 }
1804
1805 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001806 InputEventInjectionResult injectionResult;
1807 sp<WindowInfoHandle> focusedWindow =
1808 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1809 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 return false;
1812 }
1813
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001814 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 return true;
1817 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001818 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1819
1820 std::vector<InputTarget> inputTargets;
1821 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001822 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001823 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001825 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827
1828 // Dispatch the key.
1829 dispatchEventLocked(currentTime, entry, inputTargets);
1830 return true;
1831}
1832
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001833void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001834 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1835 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1836 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1837 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1838 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1839 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1840 entry.metaState, entry.repeatCount, entry.downTime);
1841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842}
1843
Prabir Pradhancef936d2021-07-21 16:17:52 +00001844void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1845 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001846 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001847 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1848 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1849 "source=0x%x, sensorType=%s",
1850 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001851 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001853 auto command = [this, entry]() REQUIRES(mLock) {
1854 scoped_unlock unlock(mLock);
1855
1856 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001857 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001858 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001859 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1860 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001861 };
1862 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001863}
1864
1865bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001866 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1867 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001868 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001869 }
Chris Yef59a2f42020-10-16 12:55:26 -07001870 { // acquire lock
1871 std::scoped_lock _l(mLock);
1872
1873 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1874 std::shared_ptr<EventEntry> entry = *it;
1875 if (entry->type == EventEntry::Type::SENSOR) {
1876 it = mInboundQueue.erase(it);
1877 releaseInboundEventLocked(entry);
1878 }
1879 }
1880 }
1881 return true;
1882}
1883
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001884bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001886 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001888 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 entry->dispatchInProgress = true;
1890
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001891 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 }
1893
1894 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001895 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001896 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001897 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1898 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 return true;
1900 }
1901
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001902 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903
1904 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001905 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906
1907 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 if (isPointerEvent) {
1910 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001911
1912 if (mDragState &&
1913 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1914 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1915 pilferPointersLocked(mDragState->dragWindow->getToken());
1916 }
1917
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001918 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001919 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001920 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001921 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1922 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 } else {
1924 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001925 sp<WindowInfoHandle> focusedWindow =
1926 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1927 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1928 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1929 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001930 InputTarget::Flags::FOREGROUND |
1931 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001932 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 return false;
1937 }
1938
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001939 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001940 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001941 return true;
1942 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001944 CancelationOptions::Mode mode(
1945 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1946 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001947 CancelationOptions options(mode, "input event injection failed");
1948 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 return true;
1950 }
1951
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001952 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001953 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954
1955 // Dispatch the motion.
1956 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001957 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 synthesizeCancelationEventsForAllConnectionsLocked(options);
1960 }
1961 dispatchEventLocked(currentTime, entry, inputTargets);
1962 return true;
1963}
1964
chaviw98318de2021-05-19 16:45:23 -05001965void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001966 bool isExiting, const int32_t rawX,
1967 const int32_t rawY) {
1968 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001969 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001970 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1971 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001972
1973 enqueueInboundEventLocked(std::move(dragEntry));
1974}
1975
1976void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1977 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1978 if (channel == nullptr) {
1979 return; // Window has gone away
1980 }
1981 InputTarget target;
1982 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001983 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001984 entry->dispatchInProgress = true;
1985 dispatchEventLocked(currentTime, entry, {target});
1986}
1987
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001988void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001990 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001992 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001993 "metaState=0x%x, buttonState=0x%x,"
1994 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001995 prefix, entry.eventTime, entry.deviceId,
1996 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1997 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1998 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1999 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002001 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002002 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002003 "x=%f, y=%f, pressure=%f, size=%f, "
2004 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2005 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002006 i, entry.pointerProperties[i].id,
2007 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2015 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2016 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019}
2020
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002021void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2022 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002023 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002024 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002025 if (DEBUG_DISPATCH_CYCLE) {
2026 ALOGD("dispatchEventToCurrentInputTargets");
2027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002029 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002030
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2032
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002033 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002035 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002036 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002037 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002038 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002039 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002041 if (DEBUG_FOCUS) {
2042 ALOGD("Dropping event delivery to target with channel '%s' because it "
2043 "is no longer registered with the input dispatcher.",
2044 inputTarget.inputChannel->getName().c_str());
2045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 }
2047 }
2048}
2049
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002050void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002051 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2052 // If the policy decides to close the app, we will get a channel removal event via
2053 // unregisterInputChannel, and will clean up the connection that way. We are already not
2054 // sending new pointers to the connection when it blocked, but focused events will continue to
2055 // pile up.
2056 ALOGW("Canceling events for %s because it is unresponsive",
2057 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002058 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002059 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002060 "application not responding");
2061 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
2063}
2064
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002065void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002066 if (DEBUG_FOCUS) {
2067 ALOGD("Resetting ANR timeouts.");
2068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069
2070 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002072 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073}
2074
Tiger Huang721e26f2018-07-24 22:26:19 +08002075/**
2076 * Get the display id that the given event should go to. If this event specifies a valid display id,
2077 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2078 * Focused display is the display that the user most recently interacted with.
2079 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002081 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002083 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002084 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2085 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002086 break;
2087 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002088 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002089 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2090 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002091 break;
2092 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002093 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002094 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002095 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002096 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002097 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002098 case EventEntry::Type::SENSOR:
2099 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002100 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002101 return ADISPLAY_ID_NONE;
2102 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002103 }
2104 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2105}
2106
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2108 const char* focusedWindowName) {
2109 if (mAnrTracker.empty()) {
2110 // already processed all events that we waited for
2111 mKeyIsWaitingForEventsTimeout = std::nullopt;
2112 return false;
2113 }
2114
2115 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2116 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002117 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002118 mKeyIsWaitingForEventsTimeout = currentTime +
2119 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2120 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 return true;
2122 }
2123
2124 // We still have pending events, and already started the timer
2125 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2126 return true; // Still waiting
2127 }
2128
2129 // Waited too long, and some connection still hasn't processed all motions
2130 // Just send the key to the focused window
2131 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2132 focusedWindowName);
2133 mKeyIsWaitingForEventsTimeout = std::nullopt;
2134 return false;
2135}
2136
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002137sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2138 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2139 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002140 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002141 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142
Tiger Huang721e26f2018-07-24 22:26:19 +08002143 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002144 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002145 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002146 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2147
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 // If there is no currently focused window and no focused application
2149 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002150 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2151 ALOGI("Dropping %s event because there is no focused window or focused application in "
2152 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002153 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002154 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
Vishnu Nair062a8672021-09-03 16:07:44 -07002157 // Drop key events if requested by input feature
2158 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002160 }
2161
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2163 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2164 // start interacting with another application via touch (app switch). This code can be removed
2165 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2166 // an app is expected to have a focused window.
2167 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2168 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2169 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002170 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2171 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2172 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002174 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 ALOGW("Waiting because no window has focus but %s may eventually add a "
2176 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002177 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002178 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 outInjectionResult = InputEventInjectionResult::PENDING;
2180 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2182 // Already raised ANR. Drop the event
2183 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002184 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002185 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186 } else {
2187 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 outInjectionResult = InputEventInjectionResult::PENDING;
2189 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002190 }
2191 }
2192
2193 // we have a valid, non-null focused window
2194 resetNoFocusedWindowTimeoutLocked();
2195
Prabir Pradhan5735a322022-04-11 17:23:34 +00002196 // Verify targeted injection.
2197 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2198 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002199 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2200 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002203 if (focusedWindowHandle->getInfo()->inputConfig.test(
2204 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002205 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002206 outInjectionResult = InputEventInjectionResult::PENDING;
2207 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002208 }
2209
2210 // If the event is a key event, then we must wait for all previous events to
2211 // complete before delivering it because previous events may have the
2212 // side-effect of transferring focus to a different window and we want to
2213 // ensure that the following keys are sent to the new window.
2214 //
2215 // Suppose the user touches a button in a window then immediately presses "A".
2216 // If the button causes a pop-up window to appear then we want to ensure that
2217 // the "A" key is delivered to the new pop-up window. This is because users
2218 // often anticipate pending UI changes when typing on a keyboard.
2219 // To obtain this behavior, we must serialize key events with respect to all
2220 // prior input events.
2221 if (entry.type == EventEntry::Type::KEY) {
2222 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2223 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002224 outInjectionResult = InputEventInjectionResult::PENDING;
2225 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002229 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2230 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231}
2232
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002233/**
2234 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2235 * that are currently unresponsive.
2236 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002237std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2238 const std::vector<Monitor>& monitors) const {
2239 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002241 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002242 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002243 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002244 if (connection == nullptr) {
2245 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002246 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 return false;
2248 }
2249 if (!connection->responsive) {
2250 ALOGW("Unresponsive monitor %s will not get the new gesture",
2251 connection->inputChannel->getName().c_str());
2252 return false;
2253 }
2254 return true;
2255 });
2256 return responsiveMonitors;
2257}
2258
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002259std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002260 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2261 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002262 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002264 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 // For security reasons, we defer updating the touch state until we are sure that
2266 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002267 const int32_t displayId = entry.displayId;
2268 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002269 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270
2271 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002272 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002274 // Copy current touch state into tempTouchState.
2275 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2276 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002277 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2280 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002281 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002282 }
2283
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002284 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002285 bool switchedDevice = false;
2286 if (oldState != nullptr) {
2287 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2288 const bool anotherDeviceIsActive =
2289 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2290 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002291 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292
2293 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2294 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2295 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002296 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2297 // touchable windows.
2298 const bool wasDown = oldState != nullptr && oldState->isDown();
2299 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2300 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002301 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2302 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2303 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002304 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002305
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002306 // If pointers are already down, let's finish the current gesture and ignore the new events
2307 // from another device. However, if the new event is a down event, let's cancel the current
2308 // touch and let the new one take over.
2309 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002310 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002311 << " is already down in display " << displayId << ": " << entry.getDescription();
2312 // TODO(b/211379801): test multiple simultaneous input streams.
2313 outInjectionResult = InputEventInjectionResult::FAILED;
2314 return {}; // wrong device
2315 }
2316
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002318 // If a new gesture is starting, clear the touch state completely.
2319 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002321 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002322 ALOGI("Dropping move event because a pointer for a different device is already active "
2323 "in display %" PRId32,
2324 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002325 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002326 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002327 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 }
2329
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002330 if (isHoverAction) {
2331 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2332 // all of the existing hovering pointers and recompute.
2333 tempTouchState.clearHoveringPointers();
2334 }
2335
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2337 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002338 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002339 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002340 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002341 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2342 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002343 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002344 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002345 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002346
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002348 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002351 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002352 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002354 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002355 }
2356
Prabir Pradhan5735a322022-04-11 17:23:34 +00002357 // Verify targeted injection.
2358 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2359 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002360 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002361 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002362 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 }
2364
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002366 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002367 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2368 // New window supports splitting, but we should never split mouse events.
2369 isSplit = !isFromMouse;
2370 } else if (isSplit) {
2371 // New window does not support splitting but we have already split events.
2372 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002373 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2374 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002375 newTouchedWindowHandle = nullptr;
2376 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002377 } else {
2378 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002379 // be delivered to a new window which supports split touch. Pointers from a mouse device
2380 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002381 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002382 }
2383
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002384 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002385 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002387 // Process the foreground window first so that it is the first to receive the event.
2388 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 }
2390
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002391 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002392 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2393 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002394 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002395 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002396 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002397 }
2398
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002400 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 continue;
2402 }
2403
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002404 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2405 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002406 // The "windowHandle" is the target of this hovering pointer.
2407 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002408 }
2409
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002411 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002413 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2414 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002416 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002417
2418 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002419 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002420 }
2421 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002424 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002426
2427 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002428 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002429 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002430 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002431 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002432
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002433 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2434 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2435
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002436 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2437 // still add a window to the touch state. We should avoid doing that, but some of the
2438 // later checks ("at least one foreground window") rely on this in order to dispatch
2439 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002440 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002441 isDownOrPointerDown
2442 ? std::make_optional(entry.eventTime)
2443 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002444
2445 // If this is the pointer going down and the touched window has a wallpaper
2446 // then also add the touched wallpaper windows so they are locked in for the duration
2447 // of the touch gesture.
2448 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2449 // engine only supports touch events. We would need to add a mechanism similar
2450 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002451 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002452 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2453 windowHandle->getInfo()->inputConfig.test(
2454 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2455 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2456 if (wallpaper != nullptr) {
2457 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2458 InputTarget::Flags::WINDOW_IS_OBSCURED |
2459 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2460 InputTarget::Flags::DISPATCH_AS_IS;
2461 if (isSplit) {
2462 wallpaperFlags |= InputTarget::Flags::SPLIT;
2463 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002464 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2465 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002466 }
2467 }
2468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002470
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002471 // If a window is already pilfering some pointers, give it this new pointer as well and
2472 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2473 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002474 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002475 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2476 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002477 // This window is already pilfering some pointers, and this new pointer is also
2478 // going to it. Therefore, take over this pointer and don't give it to anyone
2479 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002480 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002481 }
2482 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002483
2484 // Restrict all pilfered pointers to the pilfering windows.
2485 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 } else {
2487 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2488
2489 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002490 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002491 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2492 "dropped the pointer down event in display "
2493 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002494 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002495 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 }
2497
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002498 // If the pointer is not currently hovering, then ignore the event.
2499 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2500 const int32_t pointerId = entry.pointerProperties[0].id;
2501 if (oldState == nullptr ||
2502 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2503 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2504 "display "
2505 << displayId << ": " << entry.getDescription();
2506 outInjectionResult = InputEventInjectionResult::FAILED;
2507 return {};
2508 }
2509 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2510 }
2511
arthurhung6d4bed92021-03-17 11:59:33 +08002512 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002513
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002515 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002516 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002517 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002518 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002519 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002520 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002521 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002522 sp<WindowInfoHandle> newTouchedWindowHandle =
2523 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002524
Prabir Pradhan5735a322022-04-11 17:23:34 +00002525 // Verify targeted injection.
2526 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2527 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002528 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002529 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002530 }
2531
Vishnu Nair062a8672021-09-03 16:07:44 -07002532 // Drop touch events if requested by input feature
2533 if (newTouchedWindowHandle != nullptr &&
2534 shouldDropInput(entry, newTouchedWindowHandle)) {
2535 newTouchedWindowHandle = nullptr;
2536 }
2537
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002538 if (newTouchedWindowHandle != nullptr &&
2539 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002540 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2541 oldTouchedWindowHandle->getName().c_str(),
2542 newTouchedWindowHandle->getName().c_str(), displayId);
2543
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002545 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002547 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002548
2549 const TouchedWindow& touchedWindow =
2550 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2551 addWindowTargetLocked(oldTouchedWindowHandle,
2552 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002553 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554
2555 // Make a slippery entrance into the new window.
2556 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002557 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 ftl::Flags<InputTarget::Flags> targetFlags =
2561 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002562 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002563 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002566 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 }
2568 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002570 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002571 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002574 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2575 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002576
2577 // Check if the wallpaper window should deliver the corresponding event.
2578 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002579 tempTouchState, entry.deviceId, pointerId, targets);
2580 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2581 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
2583 }
Arthur Hung96483742022-11-15 03:30:48 +00002584
2585 // Update the pointerIds for non-splittable when it received pointer down.
2586 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2587 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002588 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002589 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2590 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2591 // Ignore drag window for it should just track one pointer.
2592 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2593 continue;
2594 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002595 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2596 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2597 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002598 }
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 }
2601
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002602 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002603 {
2604 std::vector<TouchedWindow> hoveringWindows =
2605 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2606 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002607 std::optional<InputTarget> target =
2608 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002609 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002610 if (!target) {
2611 continue;
2612 }
2613 // Hardcode to single hovering pointer for now.
2614 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2615 pointerIds.set(entry.pointerProperties[0].id);
2616 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2617 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620
Prabir Pradhan5735a322022-04-11 17:23:34 +00002621 // Ensure that all touched windows are valid for injection.
2622 if (entry.injectionState != nullptr) {
2623 std::string errs;
2624 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002625 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2626 if (err) errs += "\n - " + *err;
2627 }
2628 if (!errs.empty()) {
2629 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002630 "%s:%s",
2631 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002632 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002633 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002634 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002635 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002636
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002637 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2638 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002640 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002641 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002642 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002643 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002644 for (InputTarget& target : targets) {
2645 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2646 sp<WindowInfoHandle> targetWindow =
2647 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2648 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2649 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 }
2652 }
2653 }
2654 }
2655
Harry Cuttsb166c002023-05-09 13:06:05 +00002656 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2657 // only want the system UI to handle these gestures.
2658 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2659 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2660 if (isTouchpadNavGesture) {
2661 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2662 }
2663
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002664 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002665 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002666 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2667 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002668 // Windows with hovering pointers are getting persisted inside TouchState.
2669 // Do not send this event to those windows.
2670 continue;
2671 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002672
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002673 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002674 touchedWindow.getTouchingPointers(entry.deviceId),
2675 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002676 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002677
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002678 // During targeted injection, only allow owned targets to receive events
2679 std::erase_if(targets, [&](const InputTarget& target) {
2680 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2681 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2682 if (err) {
2683 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2684 << ": " << (*err);
2685 return true;
2686 }
2687 return false;
2688 });
2689
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002690 if (targets.empty()) {
2691 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2692 outInjectionResult = InputEventInjectionResult::FAILED;
2693 return {};
2694 }
2695
2696 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2697 // window that is actually receiving the entire gesture.
2698 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2699 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2700 })) {
2701 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2702 << entry.getDescription();
2703 outInjectionResult = InputEventInjectionResult::FAILED;
2704 return {};
2705 }
2706
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002707 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002708 // Drop the outside or hover touch windows since we will not care about them
2709 // in the next iteration.
2710 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002713 if (switchedDevice) {
2714 if (DEBUG_FOCUS) {
2715 ALOGD("Conflicting pointer actions: Switched to a different device.");
2716 }
2717 *outConflictingPointerActions = true;
2718 }
2719
2720 if (isHoverAction) {
2721 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002722 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002723 ALOGD_IF(DEBUG_FOCUS,
2724 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002725 *outConflictingPointerActions = true;
2726 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002727 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2728 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002729 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002730 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 // All pointers up or canceled.
2732 tempTouchState.reset();
2733 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2734 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002735 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2736 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002738 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002739 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2740 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002741 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2742 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2743 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002746 // Save changes unless the action was scroll in which case the temporary touch
2747 // state was only valid for this one action.
2748 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002749 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002750 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002751 mTouchStatesByDisplay[displayId] = tempTouchState;
2752 } else {
2753 mTouchStatesByDisplay.erase(displayId);
2754 }
2755 }
2756
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002757 if (tempTouchState.windows.empty()) {
2758 mTouchStatesByDisplay.erase(displayId);
2759 }
2760
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002761 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762}
2763
arthurhung6d4bed92021-03-17 11:59:33 +08002764void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002765 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2766 // have an explicit reason to support it.
2767 constexpr bool isStylus = false;
2768
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002769 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002770 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002771 if (dropWindow) {
2772 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002773 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002774 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002775 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002776 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002777 }
2778 mDragState.reset();
2779}
2780
2781void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002782 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002783 return;
2784 }
2785
arthurhung6d4bed92021-03-17 11:59:33 +08002786 if (!mDragState->isStartDrag) {
2787 mDragState->isStartDrag = true;
2788 mDragState->isStylusButtonDownAtStart =
2789 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2790 }
2791
Arthur Hung54745652022-04-20 07:17:41 +00002792 // Find the pointer index by id.
2793 int32_t pointerIndex = 0;
2794 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2795 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2796 if (pointerProperties.id == mDragState->pointerId) {
2797 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002798 }
Arthur Hung54745652022-04-20 07:17:41 +00002799 }
arthurhung6d4bed92021-03-17 11:59:33 +08002800
Arthur Hung54745652022-04-20 07:17:41 +00002801 if (uint32_t(pointerIndex) == entry.pointerCount) {
2802 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002803 }
2804
2805 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2806 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2807 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2808
2809 switch (maskedAction) {
2810 case AMOTION_EVENT_ACTION_MOVE: {
2811 // Handle the special case : stylus button no longer pressed.
2812 bool isStylusButtonDown =
2813 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2814 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2815 finishDragAndDrop(entry.displayId, x, y);
2816 return;
2817 }
2818
2819 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2820 // until we have an explicit reason to support it.
2821 constexpr bool isStylus = false;
2822
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002823 sp<WindowInfoHandle> hoverWindowHandle =
2824 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2825 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002826 // enqueue drag exit if needed.
2827 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2828 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2829 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002830 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002831 y);
2832 }
2833 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2834 }
2835 // enqueue drag location if needed.
2836 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002837 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002838 }
2839 break;
2840 }
2841
2842 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002843 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002844 break;
2845 }
2846 // The drag pointer is up.
2847 [[fallthrough]];
2848 case AMOTION_EVENT_ACTION_UP:
2849 finishDragAndDrop(entry.displayId, x, y);
2850 break;
2851 case AMOTION_EVENT_ACTION_CANCEL: {
2852 ALOGD("Receiving cancel when drag and drop.");
2853 sendDropWindowCommandLocked(nullptr, 0, 0);
2854 mDragState.reset();
2855 break;
2856 }
arthurhungb89ccb02020-12-30 16:19:01 +08002857 }
2858}
2859
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002860std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2861 const sp<android::gui::WindowInfoHandle>& windowHandle,
2862 ftl::Flags<InputTarget::Flags> targetFlags,
2863 std::optional<nsecs_t> firstDownTimeInTarget) const {
2864 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2865 if (inputChannel == nullptr) {
2866 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2867 return {};
2868 }
2869 InputTarget inputTarget;
2870 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002871 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 inputTarget.flags = targetFlags;
2873 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2874 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2875 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2876 if (displayInfoIt != mDisplayInfos.end()) {
2877 inputTarget.displayTransform = displayInfoIt->second.transform;
2878 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002879 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002880 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2881 }
2882 return inputTarget;
2883}
2884
chaviw98318de2021-05-19 16:45:23 -05002885void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002886 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002887 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002888 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002889 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002890 std::vector<InputTarget>::iterator it =
2891 std::find_if(inputTargets.begin(), inputTargets.end(),
2892 [&windowHandle](const InputTarget& inputTarget) {
2893 return inputTarget.inputChannel->getConnectionToken() ==
2894 windowHandle->getToken();
2895 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002896
chaviw98318de2021-05-19 16:45:23 -05002897 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002898
2899 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002900 std::optional<InputTarget> target =
2901 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2902 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002903 return;
2904 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002905 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002906 it = inputTargets.end() - 1;
2907 }
2908
2909 ALOG_ASSERT(it->flags == targetFlags);
2910 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2911
chaviw1ff3d1e2020-07-01 15:53:47 -07002912 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913}
2914
Michael Wright3dd60e22019-03-27 22:06:44 +00002915void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002916 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002917 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2918 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002919
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002920 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2921 InputTarget target;
2922 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002923 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002924 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2925 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002926 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2927 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002928 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002929 target.setDefaultPointerTransform(target.displayTransform);
2930 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
2932}
2933
Robert Carrc9bf1d32020-04-13 17:21:08 -07002934/**
2935 * Indicate whether one window handle should be considered as obscuring
2936 * another window handle. We only check a few preconditions. Actually
2937 * checking the bounds is left to the caller.
2938 */
chaviw98318de2021-05-19 16:45:23 -05002939static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2940 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002941 // Compare by token so cloned layers aren't counted
2942 if (haveSameToken(windowHandle, otherHandle)) {
2943 return false;
2944 }
2945 auto info = windowHandle->getInfo();
2946 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002948 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002949 } else if (otherInfo->alpha == 0 &&
2950 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002951 // Those act as if they were invisible, so we don't need to flag them.
2952 // We do want to potentially flag touchable windows even if they have 0
2953 // opacity, since they can consume touches and alter the effects of the
2954 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002955 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002956 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2957 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002958 } else if (info->ownerUid == otherInfo->ownerUid) {
2959 // If ownerUid is the same we don't generate occlusion events as there
2960 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002961 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002962 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002963 return false;
2964 } else if (otherInfo->displayId != info->displayId) {
2965 return false;
2966 }
2967 return true;
2968}
2969
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002970/**
2971 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2972 * untrusted, one should check:
2973 *
2974 * 1. If result.hasBlockingOcclusion is true.
2975 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2976 * BLOCK_UNTRUSTED.
2977 *
2978 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2979 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2980 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2981 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2982 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2983 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2984 *
2985 * If neither of those is true, then it means the touch can be allowed.
2986 */
2987InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002988 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2989 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002990 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002991 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002992 TouchOcclusionInfo info;
2993 info.hasBlockingOcclusion = false;
2994 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002995 info.obscuringUid = gui::Uid::INVALID;
2996 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002997 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002998 if (windowHandle == otherHandle) {
2999 break; // All future windows are below us. Exit early.
3000 }
chaviw98318de2021-05-19 16:45:23 -05003001 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003002 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3003 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003004 if (DEBUG_TOUCH_OCCLUSION) {
3005 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003006 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003007 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003008 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3009 // we perform the checks below to see if the touch can be propagated or not based on the
3010 // window's touch occlusion mode
3011 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3012 info.hasBlockingOcclusion = true;
3013 info.obscuringUid = otherInfo->ownerUid;
3014 info.obscuringPackage = otherInfo->packageName;
3015 break;
3016 }
3017 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003018 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003019 float opacity =
3020 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3021 // Given windows A and B:
3022 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3023 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3024 opacityByUid[uid] = opacity;
3025 if (opacity > info.obscuringOpacity) {
3026 info.obscuringOpacity = opacity;
3027 info.obscuringUid = uid;
3028 info.obscuringPackage = otherInfo->packageName;
3029 }
3030 }
3031 }
3032 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003034 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003035 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003036 return info;
3037}
3038
chaviw98318de2021-05-19 16:45:23 -05003039std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003040 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003041 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003042 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3043 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3044 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003045 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003046 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003047 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3048 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003049 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3050 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3051 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003052 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003053}
3054
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003055bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3056 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003057 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3058 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003059 return false;
3060 }
3061 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003062 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003064 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003065 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3066 return false;
3067 }
3068 return true;
3069}
3070
chaviw98318de2021-05-19 16:45:23 -05003071bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003074 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3075 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003076 if (windowHandle == otherHandle) {
3077 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 }
chaviw98318de2021-05-19 16:45:23 -05003079 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003080 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003081 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 return true;
3083 }
3084 }
3085 return false;
3086}
3087
chaviw98318de2021-05-19 16:45:23 -05003088bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003089 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003090 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3091 const WindowInfo* windowInfo = windowHandle->getInfo();
3092 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003093 if (windowHandle == otherHandle) {
3094 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003095 }
chaviw98318de2021-05-19 16:45:23 -05003096 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003097 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003098 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003099 return true;
3100 }
3101 }
3102 return false;
3103}
3104
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003105std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003106 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003107 if (applicationHandle != nullptr) {
3108 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003109 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 } else {
3111 return applicationHandle->getName();
3112 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003113 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003114 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003116 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118}
3119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003120void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003121 if (!isUserActivityEvent(eventEntry)) {
3122 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003123 return;
3124 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003125 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003126 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003127 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003128 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003129 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003130 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003131 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
3133 }
3134
3135 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003137 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003138 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3139 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 return;
3141 }
Josep del Riob3981622023-04-18 15:49:45 +00003142 if (windowDisablingUserActivityInfo != nullptr) {
3143 if (DEBUG_DISPATCH_CYCLE) {
3144 ALOGD("Not poking user activity: disabled by window '%s'.",
3145 windowDisablingUserActivityInfo->name.c_str());
3146 }
3147 return;
3148 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003149 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 eventType = USER_ACTIVITY_EVENT_TOUCH;
3151 }
3152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003154 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003155 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3156 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 return;
3158 }
Josep del Riob3981622023-04-18 15:49:45 +00003159 // If the key code is unknown, we don't consider it user activity
3160 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3161 return;
3162 }
3163 // Don't inhibit events that were intercepted or are not passed to
3164 // the apps, like system shortcuts
3165 if (windowDisablingUserActivityInfo != nullptr &&
3166 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3167 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3168 if (DEBUG_DISPATCH_CYCLE) {
3169 ALOGD("Not poking user activity: disabled by window '%s'.",
3170 windowDisablingUserActivityInfo->name.c_str());
3171 }
3172 return;
3173 }
3174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 eventType = USER_ACTIVITY_EVENT_BUTTON;
3176 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003178 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003180 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 break;
3182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 }
3184
Prabir Pradhancef936d2021-07-21 16:17:52 +00003185 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3186 REQUIRES(mLock) {
3187 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003188 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003189 };
3190 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191}
3192
3193void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003194 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003195 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003196 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003197 ATRACE_NAME_IF(ATRACE_ENABLED(),
3198 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3199 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003202 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003203 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003204 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003205 inputTarget.getPointerInfoString().c_str());
3206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207
3208 // Skip this event if the connection status is not normal.
3209 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003210 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003211 if (DEBUG_DISPATCH_CYCLE) {
3212 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003213 connection->getInputChannelName().c_str(),
3214 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 return;
3217 }
3218
3219 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003221 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003223 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003225 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003226 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003227 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3228 logDispatchStateLocked();
3229 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3230 "target on connection "
3231 << connection->getInputChannelName() << " for "
3232 << originalMotionEntry.getDescription();
3233 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003235 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3236 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 if (!splitMotionEntry) {
3238 return; // split event was dropped
3239 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003240 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3241 std::string reason = std::string("reason=pointer cancel on split window");
3242 android_log_event_list(LOGTAG_INPUT_CANCEL)
3243 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3244 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003245 if (DEBUG_FOCUS) {
3246 ALOGD("channel '%s' ~ Split motion event.",
3247 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003248 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003249 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3251 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 return;
3253 }
3254 }
3255
3256 // Not splitting. Enqueue dispatch entries for the event as is.
3257 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3258}
3259
3260void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003261 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003262 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003263 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003264 ATRACE_NAME_IF(ATRACE_ENABLED(),
3265 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3266 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003267 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3268 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003269
hongzuo liu95785e22022-09-06 02:51:35 +00003270 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 startDispatchCycleLocked(currentTime, connection);
3289 }
3290}
3291
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003292void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003294 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003295 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3297 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 return;
3299 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003300
3301 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3302 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
3304 // This is a new event.
3305 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003306 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003309 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3310 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003314 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3317 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003318 LOG(WARNING) << "channel " << connection->getInputChannelName()
3319 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 return; // skip the inconsistent event
3321 }
3322 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003325 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003326 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003327 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3328 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3329 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3330 static_cast<int32_t>(IdGenerator::Source::OTHER);
3331 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3342 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003343 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 }
3345 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003346 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3347 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003348 if (DEBUG_DISPATCH_CYCLE) {
3349 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3350 "enter event",
3351 connection->getInputChannelName().c_str());
3352 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003353 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3354 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003358 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3359 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3360 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003361 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3363 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003364 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3369 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003370 LOG(WARNING) << "channel " << connection->getInputChannelName()
3371 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 return; // skip the inconsistent event
3373 }
3374
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003375 dispatchEntry->resolvedEventId =
3376 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3377 ? mIdGenerator.nextId()
3378 : motionEntry.id;
3379 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3380 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3381 ") to MotionEvent(id=0x%" PRIx32 ").",
3382 motionEntry.id, dispatchEntry->resolvedEventId);
3383 ATRACE_NAME(message.c_str());
3384 }
3385
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003386 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3387 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3388 // Skip reporting pointer down outside focus to the policy.
3389 break;
3390 }
3391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003392 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003393 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394
3395 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003397 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003398 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003399 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3400 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003401 break;
3402 }
Chris Yef59a2f42020-10-16 12:55:26 -07003403 case EventEntry::Type::SENSOR: {
3404 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3405 break;
3406 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003407 case EventEntry::Type::CONFIGURATION_CHANGED:
3408 case EventEntry::Type::DEVICE_RESET: {
3409 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003410 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 break;
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414
3415 // Remember that we are waiting for this dispatch to complete.
3416 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003417 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 }
3419
3420 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003421 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003422 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003423}
3424
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003425/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003426 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003427 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003428 * The first role is to log input interaction with windows, which helps determine what the user was
3429 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3430 * that user started interacting with launcher window, as well as any other window that received
3431 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3432 * when the set of tokens that received the event changes. It is not logged again as long as the
3433 * user is interacting with the same windows.
3434 *
3435 * The second role is to track input device activity for metrics collection. For each input event,
3436 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3437 * input_interaction logs, the device interaction is reported even when the set of interaction
3438 * tokens do not change.
3439 *
3440 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3441 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003442 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003443void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3444 const std::vector<InputTarget>& targets) {
3445 int32_t deviceId;
3446 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003447 // Skip ACTION_UP events, and all events other than keys and motions
3448 if (entry.type == EventEntry::Type::KEY) {
3449 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3450 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3451 return;
3452 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003453 deviceId = keyEntry.deviceId;
3454 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003455 } else if (entry.type == EventEntry::Type::MOTION) {
3456 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3457 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003458 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3459 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003460 return;
3461 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003462 deviceId = motionEntry.deviceId;
3463 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003464 } else {
3465 return; // Not a key or a motion
3466 }
3467
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003468 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003469 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003470 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003471 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003472 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003473 continue; // Skip windows that receive ACTION_OUTSIDE
3474 }
3475
3476 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003477 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003478 if (connection == nullptr) {
3479 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003480 }
3481 newConnectionTokens.insert(std::move(token));
3482 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003483 if (target.windowHandle) {
3484 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3485 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003486 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003487
3488 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3489 REQUIRES(mLock) {
3490 scoped_unlock unlock(mLock);
3491 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3492 };
3493 postCommandLocked(std::move(command));
3494
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003495 if (newConnectionTokens == mInteractionConnectionTokens) {
3496 return; // no change
3497 }
3498 mInteractionConnectionTokens = newConnectionTokens;
3499
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003500 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003501 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003503 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003504 std::string message = "Interaction with: " + targetList;
3505 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003506 message += "<none>";
3507 }
3508 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3509}
3510
chaviwfd6d3512019-03-25 13:23:49 -07003511void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003512 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003513 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003514 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3515 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003516 return;
3517 }
3518
Vishnu Nairc519ff72021-01-21 08:23:08 -08003519 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003520 if (focusedToken == token) {
3521 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003522 return;
3523 }
3524
Prabir Pradhancef936d2021-07-21 16:17:52 +00003525 auto command = [this, token]() REQUIRES(mLock) {
3526 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003527 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003528 };
3529 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530}
3531
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003532status_t InputDispatcher::publishMotionEvent(Connection& connection,
3533 DispatchEntry& dispatchEntry) const {
3534 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3535 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3536
3537 PointerCoords scaledCoords[MAX_POINTERS];
3538 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3539
3540 // Set the X and Y offset and X and Y scale depending on the input source.
3541 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003542 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003543 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3544 if (globalScaleFactor != 1.0f) {
3545 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3546 scaledCoords[i] = motionEntry.pointerCoords[i];
3547 // Don't apply window scale here since we don't want scale to affect raw
3548 // coordinates. The scale will be sent back to the client and applied
3549 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003550 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003551 }
3552 usingCoords = scaledCoords;
3553 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003554 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003555 // We don't want the dispatch target to know the coordinates
3556 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3557 scaledCoords[i].clear();
3558 }
3559 usingCoords = scaledCoords;
3560 }
3561
3562 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3563
3564 // Publish the motion event.
3565 return connection.inputPublisher
3566 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3567 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3568 std::move(hmac), dispatchEntry.resolvedAction,
3569 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3570 motionEntry.edgeFlags, motionEntry.metaState,
3571 motionEntry.buttonState, motionEntry.classification,
3572 dispatchEntry.transform, motionEntry.xPrecision,
3573 motionEntry.yPrecision, motionEntry.xCursorPosition,
3574 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3575 motionEntry.downTime, motionEntry.eventTime,
3576 motionEntry.pointerCount, motionEntry.pointerProperties,
3577 usingCoords);
3578}
3579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003581 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003582 ATRACE_NAME_IF(ATRACE_ENABLED(),
3583 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3584 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003585 if (DEBUG_DISPATCH_CYCLE) {
3586 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003589 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003590 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003592 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003593 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
3595 // Publish the event.
3596 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003597 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3598 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003599 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003600 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3601 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003602 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003603 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3604 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003608 status = connection->inputPublisher
3609 .publishKeyEvent(dispatchEntry->seq,
3610 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3611 keyEntry.source, keyEntry.displayId,
3612 std::move(hmac), dispatchEntry->resolvedAction,
3613 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3614 keyEntry.scanCode, keyEntry.metaState,
3615 keyEntry.repeatCount, keyEntry.downTime,
3616 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003617 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003620 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003621 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003622 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3623 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003624 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003625 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626 break;
3627 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003629 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003631 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003633 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003634 break;
3635 }
3636
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003637 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3638 const TouchModeEntry& touchModeEntry =
3639 static_cast<const TouchModeEntry&>(eventEntry);
3640 status = connection->inputPublisher
3641 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3642 touchModeEntry.inTouchMode);
3643
3644 break;
3645 }
3646
Prabir Pradhan99987712020-11-10 18:43:05 -08003647 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3648 const auto& captureEntry =
3649 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3650 status = connection->inputPublisher
3651 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003652 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 break;
3654 }
3655
arthurhungb89ccb02020-12-30 16:19:01 +08003656 case EventEntry::Type::DRAG: {
3657 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3658 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3659 dragEntry.id, dragEntry.x,
3660 dragEntry.y,
3661 dragEntry.isExiting);
3662 break;
3663 }
3664
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003665 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003666 case EventEntry::Type::DEVICE_RESET:
3667 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003668 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003669 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673
3674 // Check the result.
3675 if (status) {
3676 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003677 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003679 "This is unexpected because the wait queue is empty, so the pipe "
3680 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003681 "event to it, status=%s(%d)",
3682 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3683 status);
Harry Cutts33476232023-01-30 19:57:29 +00003684 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 } else {
3686 // Pipe is full and we are waiting for the app to finish process some events
3687 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003688 if (DEBUG_DISPATCH_CYCLE) {
3689 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3690 "waiting for the application to catch up",
3691 connection->getInputChannelName().c_str());
3692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
3694 } else {
3695 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003696 "status=%s(%d)",
3697 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3698 status);
Harry Cutts33476232023-01-30 19:57:29 +00003699 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701 return;
3702 }
3703
3704 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003705 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3706 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3707 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003708 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003709 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003710 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003711 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003712 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 }
3714}
3715
chaviw09c8d2d2020-08-24 15:48:26 -07003716std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3717 size_t size;
3718 switch (event.type) {
3719 case VerifiedInputEvent::Type::KEY: {
3720 size = sizeof(VerifiedKeyEvent);
3721 break;
3722 }
3723 case VerifiedInputEvent::Type::MOTION: {
3724 size = sizeof(VerifiedMotionEvent);
3725 break;
3726 }
3727 }
3728 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3729 return mHmacKeyManager.sign(start, size);
3730}
3731
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003732const std::array<uint8_t, 32> InputDispatcher::getSignature(
3733 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003734 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003735 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003736 // Only sign events up and down events as the purely move events
3737 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003739 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003740
3741 VerifiedMotionEvent verifiedEvent =
3742 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3743 verifiedEvent.actionMasked = actionMasked;
3744 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3745 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003746}
3747
3748const std::array<uint8_t, 32> InputDispatcher::getSignature(
3749 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3750 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3751 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3752 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003753 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003754}
3755
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003757 const std::shared_ptr<Connection>& connection,
3758 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003759 if (DEBUG_DISPATCH_CYCLE) {
3760 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3761 connection->getInputChannelName().c_str(), seq, toString(handled));
3762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003764 if (connection->status == Connection::Status::BROKEN ||
3765 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 return;
3767 }
3768
3769 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003770 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3771 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3772 };
3773 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774}
3775
3776void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003777 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003778 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003779 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003780 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3781 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
3784 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003787 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003788 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
3790 // The connection appears to be unrecoverably broken.
3791 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003792 if (connection->status == Connection::Status::NORMAL) {
3793 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794
3795 if (notify) {
3796 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003797 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3798 connection->getInputChannelName().c_str());
3799
3800 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003802 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003803 };
3804 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806 }
3807}
3808
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003810 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003811 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003812 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814}
3815
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003816void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003818 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820}
3821
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003822int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3823 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003824 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 if (connection == nullptr) {
3826 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3827 connectionToken.get(), events);
3828 return 0; // remove the callback
3829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003831 bool notify;
3832 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3833 if (!(events & ALOOPER_EVENT_INPUT)) {
3834 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3835 "events=0x%x",
3836 connection->getInputChannelName().c_str(), events);
3837 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003840 nsecs_t currentTime = now();
3841 bool gotOne = false;
3842 status_t status = OK;
3843 for (;;) {
3844 Result<InputPublisher::ConsumerResponse> result =
3845 connection->inputPublisher.receiveConsumerResponse();
3846 if (!result.ok()) {
3847 status = result.error().code();
3848 break;
3849 }
3850
3851 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3852 const InputPublisher::Finished& finish =
3853 std::get<InputPublisher::Finished>(*result);
3854 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3855 finish.consumeTime);
3856 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003857 if (shouldReportMetricsForConnection(*connection)) {
3858 const InputPublisher::Timeline& timeline =
3859 std::get<InputPublisher::Timeline>(*result);
3860 mLatencyTracker
3861 .trackGraphicsLatency(timeline.inputEventId,
3862 connection->inputChannel->getConnectionToken(),
3863 std::move(timeline.graphicsTimeline));
3864 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003865 }
3866 gotOne = true;
3867 }
3868 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003869 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003870 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 return 1;
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 notify = status != DEAD_OBJECT || !connection->monitor;
3876 if (notify) {
3877 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3878 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3879 status);
3880 }
3881 } else {
3882 // Monitor channels are never explicitly unregistered.
3883 // We do it automatically when the remote endpoint is closed so don't warn about them.
3884 const bool stillHaveWindowHandle =
3885 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3886 notify = !connection->monitor && stillHaveWindowHandle;
3887 if (notify) {
3888 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3889 connection->getInputChannelName().c_str(), events);
3890 }
3891 }
3892
3893 // Remove the channel.
3894 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3895 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896}
3897
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003898void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003900 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003901 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
3903}
3904
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003906 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003907 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003908 for (const Monitor& monitor : monitors) {
3909 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003910 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003911 }
3912}
3913
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003915 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003916 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003917 if (connection == nullptr) {
3918 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003920
3921 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922}
3923
3924void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003925 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003926 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 return;
3928 }
3929
3930 nsecs_t currentTime = now();
3931
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003932 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003933 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003935 if (cancelationEvents.empty()) {
3936 return;
3937 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003938 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3939 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003940 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003942 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003943 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944
Arthur Hungb3307ee2021-10-14 10:57:37 +00003945 std::string reason = std::string("reason=").append(options.reason);
3946 android_log_event_list(LOGTAG_INPUT_CANCEL)
3947 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3948
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 InputTarget target;
Hu Guo771a7692023-09-17 20:51:08 +08003950 sp<WindowInfoHandle> windowHandle;
3951 if (options.displayId) {
3952 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3953 options.displayId.value());
3954 } else {
3955 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3956 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003957 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003958 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003959 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003960 target.globalScaleFactor = windowInfo->globalScaleFactor;
3961 }
3962 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003963 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003964
hongzuo liu95785e22022-09-06 02:51:35 +00003965 const bool wasEmpty = connection->outboundQueue.empty();
3966
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003967 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003969 switch (cancelationEventEntry->type) {
3970 case EventEntry::Type::KEY: {
3971 logOutboundKeyDetails("cancel - ",
3972 static_cast<const KeyEntry&>(*cancelationEventEntry));
3973 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003975 case EventEntry::Type::MOTION: {
3976 logOutboundMotionDetails("cancel - ",
3977 static_cast<const MotionEntry&>(*cancelationEventEntry));
3978 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003980 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003981 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003982 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3983 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003984 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003985 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 break;
3987 }
3988 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003989 case EventEntry::Type::DEVICE_RESET:
3990 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003991 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003992 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003993 break;
3994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 }
3996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003997 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003998 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004000
hongzuo liu95785e22022-09-06 02:51:35 +00004001 // If the outbound queue was previously empty, start the dispatch cycle going.
4002 if (wasEmpty && !connection->outboundQueue.empty()) {
4003 startDispatchCycleLocked(currentTime, connection);
4004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005}
4006
Svet Ganov5d3bc372020-01-26 23:11:07 -08004007void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004008 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004009 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004010 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004011 return;
4012 }
4013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004014 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004015 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004016
4017 if (downEvents.empty()) {
4018 return;
4019 }
4020
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004022 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4023 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004024 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004025
4026 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004027 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004028 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4029 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004030 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004031 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004032 target.globalScaleFactor = windowInfo->globalScaleFactor;
4033 }
4034 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004035 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036
hongzuo liu95785e22022-09-06 02:51:35 +00004037 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004038 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004039 switch (downEventEntry->type) {
4040 case EventEntry::Type::MOTION: {
4041 logOutboundMotionDetails("down - ",
4042 static_cast<const MotionEntry&>(*downEventEntry));
4043 break;
4044 }
4045
4046 case EventEntry::Type::KEY:
4047 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004048 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004050 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004051 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004052 case EventEntry::Type::SENSOR:
4053 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004055 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004056 break;
4057 }
4058 }
4059
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004060 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004061 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004062 }
4063
hongzuo liu95785e22022-09-06 02:51:35 +00004064 // If the outbound queue was previously empty, start the dispatch cycle going.
4065 if (wasEmpty && !connection->outboundQueue.empty()) {
4066 startDispatchCycleLocked(downTime, connection);
4067 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004068}
4069
Arthur Hungc539dbb2022-12-08 07:45:36 +00004070void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4071 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4072 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004073 std::shared_ptr<Connection> wallpaperConnection =
4074 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004075 if (wallpaperConnection != nullptr) {
4076 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4077 }
4078 }
4079}
4080
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004082 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4083 nsecs_t splitDownTime) {
4084 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
4086 uint32_t splitPointerIndexMap[MAX_POINTERS];
4087 PointerProperties splitPointerProperties[MAX_POINTERS];
4088 PointerCoords splitPointerCoords[MAX_POINTERS];
4089
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004090 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 uint32_t splitPointerCount = 0;
4092
4093 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004096 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004098 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004100 splitPointerProperties[splitPointerCount] = pointerProperties;
4101 splitPointerCoords[splitPointerCount] =
4102 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 splitPointerCount += 1;
4104 }
4105 }
4106
4107 if (splitPointerCount != pointerIds.count()) {
4108 // This is bad. We are missing some of the pointers that we expected to deliver.
4109 // Most likely this indicates that we received an ACTION_MOVE events that has
4110 // different pointer ids than we expected based on the previous ACTION_DOWN
4111 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4112 // in this way.
4113 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004114 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004115 "a broken sequence of pointer ids from the input device: %s",
4116 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004117 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
4119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004120 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4123 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004124 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004126 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004128 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 if (pointerIds.count() == 1) {
4130 // The first/last pointer went down/up.
4131 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004133 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4134 ? AMOTION_EVENT_ACTION_CANCEL
4135 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 } else {
4137 // A secondary pointer went down/up.
4138 uint32_t splitPointerIndex = 0;
4139 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4140 splitPointerIndex += 1;
4141 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 action = maskedAction |
4143 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 }
4145 } else {
4146 // An unrelated pointer changed.
4147 action = AMOTION_EVENT_ACTION_MOVE;
4148 }
4149 }
4150
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004151 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4152 logDispatchStateLocked();
4153 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4154 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4155 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004156 }
4157
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004158 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004159 ATRACE_NAME_IF(ATRACE_ENABLED(),
4160 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4161 ").",
4162 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004163 std::unique_ptr<MotionEntry> splitMotionEntry =
4164 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4165 originalMotionEntry.deviceId, originalMotionEntry.source,
4166 originalMotionEntry.displayId,
4167 originalMotionEntry.policyFlags, action,
4168 originalMotionEntry.actionButton,
4169 originalMotionEntry.flags, originalMotionEntry.metaState,
4170 originalMotionEntry.buttonState,
4171 originalMotionEntry.classification,
4172 originalMotionEntry.edgeFlags,
4173 originalMotionEntry.xPrecision,
4174 originalMotionEntry.yPrecision,
4175 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004176 originalMotionEntry.yCursorPosition, splitDownTime,
4177 splitPointerCount, splitPointerProperties,
4178 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004180 if (originalMotionEntry.injectionState) {
4181 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 splitMotionEntry->injectionState->refCount += 1;
4183 }
4184
4185 return splitMotionEntry;
4186}
4187
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004188void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004189 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004190 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192
Antonio Kantekf16f2832021-09-28 04:39:20 +00004193 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004195 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004198 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004199 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 } // release lock
4201
4202 if (needWake) {
4203 mLooper->wake();
4204 }
4205}
4206
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004207void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004208 ALOGD_IF(debugInboundEventDetails(),
4209 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4210 ", deviceId=%d, source=%s, displayId=%" PRId32
4211 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4212 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004213 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4214 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4215 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004216 Result<void> keyCheck = validateKeyEvent(args.action);
4217 if (!keyCheck.ok()) {
4218 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 return;
4220 }
4221
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004222 uint32_t policyFlags = args.policyFlags;
4223 int32_t flags = args.flags;
4224 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004225 // InputDispatcher tracks and generates key repeats on behalf of
4226 // whatever notifies it, so repeatCount should always be set to 0
4227 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4229 policyFlags |= POLICY_FLAG_VIRTUAL;
4230 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 if (policyFlags & POLICY_FLAG_FUNCTION) {
4233 metaState |= AMETA_FUNCTION_ON;
4234 }
4235
4236 policyFlags |= POLICY_FLAG_TRUSTED;
4237
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004238 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004240 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4241 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4242 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243
Michael Wright2b3c3302018-03-02 17:19:13 +00004244 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004245 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004246 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4247 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250
Antonio Kantekf16f2832021-09-28 04:39:20 +00004251 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 { // acquire lock
4253 mLock.lock();
4254
4255 if (shouldSendKeyToInputFilterLocked(args)) {
4256 mLock.unlock();
4257
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004258 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004259 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 return; // event was consumed by the filter
4261 }
4262
4263 mLock.lock();
4264 }
4265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004266 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004267 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4268 args.displayId, policyFlags, args.action, flags, keyCode,
4269 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 mLock.unlock();
4273 } // release lock
4274
4275 if (needWake) {
4276 mLooper->wake();
4277 }
4278}
4279
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004280bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 return mInputFilterEnabled;
4282}
4283
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004284void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004285 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004286 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004287 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004288 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004289 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4290 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004291 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4292 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4293 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4294 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4295 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004296 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004297 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4298 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004299 i, args.pointerProperties[i].id,
4300 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4301 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4302 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4303 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4304 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4305 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4306 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4307 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4308 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4309 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004312
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004313 Result<void> motionCheck =
4314 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4315 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004316 if (!motionCheck.ok()) {
4317 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4318 return;
4319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004321 if (DEBUG_VERIFY_EVENTS) {
4322 auto [it, _] =
4323 mVerifiersByDisplay.try_emplace(args.displayId,
4324 StringPrintf("display %" PRId32, args.displayId));
4325 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004326 it->second.processMovement(args.deviceId, args.source, args.action,
4327 args.getPointerCount(), args.pointerProperties.data(),
4328 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004329 if (!result.ok()) {
4330 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4331 }
4332 }
4333
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004334 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004336
4337 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004338 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004339 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4340 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004341 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
Antonio Kantekf16f2832021-09-28 04:39:20 +00004344 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 { // acquire lock
4346 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004347 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4348 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4349 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004350 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004351 if (touchStateIt != mTouchStatesByDisplay.end()) {
4352 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004353 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004354 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4355 }
4356 }
4357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
4359 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004360 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004361 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004362 displayTransform = it->second.transform;
4363 }
4364
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 mLock.unlock();
4366
4367 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004368 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4369 args.action, args.actionButton, args.flags, args.edgeFlags,
4370 args.metaState, args.buttonState, args.classification,
4371 displayTransform, args.xPrecision, args.yPrecision,
4372 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004373 args.downTime, args.eventTime, args.getPointerCount(),
4374 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
4376 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004377 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 return; // event was consumed by the filter
4379 }
4380
4381 mLock.lock();
4382 }
4383
4384 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004385 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004386 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4387 args.displayId, policyFlags, args.action,
4388 args.actionButton, args.flags, args.metaState,
4389 args.buttonState, args.classification, args.edgeFlags,
4390 args.xPrecision, args.yPrecision,
4391 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004392 args.downTime, args.getPointerCount(),
4393 args.pointerProperties.data(),
4394 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004396 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4397 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004398 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004399 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4400 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004401 }
4402
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004403 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 mLock.unlock();
4405 } // release lock
4406
4407 if (needWake) {
4408 mLooper->wake();
4409 }
4410}
4411
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004412void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004413 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004414 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4415 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004416 args.id, args.eventTime, args.deviceId, args.source,
4417 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004418 }
Chris Yef59a2f42020-10-16 12:55:26 -07004419
Antonio Kantekf16f2832021-09-28 04:39:20 +00004420 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004421 { // acquire lock
4422 mLock.lock();
4423
4424 // Just enqueue a new sensor event.
4425 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004426 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4427 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4428 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004429
4430 needWake = enqueueInboundEventLocked(std::move(newEntry));
4431 mLock.unlock();
4432 } // release lock
4433
4434 if (needWake) {
4435 mLooper->wake();
4436 }
4437}
4438
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004440 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004441 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4442 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004444 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004445}
4446
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004447bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004448 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449}
4450
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004451void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004452 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004453 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4454 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004455 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004458 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004460 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461}
4462
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004463void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004464 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4466 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468
Antonio Kantekf16f2832021-09-28 04:39:20 +00004469 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004471 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004473 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004474 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004475 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004476
4477 for (auto& [_, verifier] : mVerifiersByDisplay) {
4478 verifier.resetDevice(args.deviceId);
4479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 } // release lock
4481
4482 if (needWake) {
4483 mLooper->wake();
4484 }
4485}
4486
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004488 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004489 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4490 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004491 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004492
Antonio Kantekf16f2832021-09-28 04:39:20 +00004493 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004494 { // acquire lock
4495 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004496 auto entry =
4497 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004498 needWake = enqueueInboundEventLocked(std::move(entry));
4499 } // release lock
4500
4501 if (needWake) {
4502 mLooper->wake();
4503 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004504}
4505
Prabir Pradhan5735a322022-04-11 17:23:34 +00004506InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004507 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004508 InputEventInjectionSync syncMode,
4509 std::chrono::milliseconds timeout,
4510 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004511 Result<void> eventValidation = validateInputEvent(*event);
4512 if (!eventValidation.ok()) {
4513 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4514 return InputEventInjectionResult::FAILED;
4515 }
4516
Prabir Pradhan65613802023-02-22 23:36:58 +00004517 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004518 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4519 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4520 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4521 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004522 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004523 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
Prabir Pradhan5735a322022-04-11 17:23:34 +00004525 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004527 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004528 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4529 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4530 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4531 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4532 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004533 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004534 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004535 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004536 }
4537
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004538 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004540 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004541 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004542 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004543 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004544 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4545 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4546 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004547 int32_t keyCode = incomingKey.getKeyCode();
4548 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004549 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004550 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004551 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4552 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4553 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004555 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4556 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004557 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004558
4559 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4560 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004561 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4563 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4564 std::to_string(t.duration().count()).c_str());
4565 }
4566 }
4567
4568 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004569 std::unique_ptr<KeyEntry> injectedEntry =
4570 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004571 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004572 incomingKey.getDisplayId(), policyFlags, action,
4573 flags, keyCode, incomingKey.getScanCode(), metaState,
4574 incomingKey.getRepeatCount(),
4575 incomingKey.getDownTime());
4576 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004577 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004580 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004581 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004582 const bool isPointerEvent =
4583 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4584 // If a pointer event has no displayId specified, inject it to the default display.
4585 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4586 ? ADISPLAY_ID_DEFAULT
4587 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004588 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004589
4590 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004591 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004592 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004593 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4595 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4596 std::to_string(t.duration().count()).c_str());
4597 }
4598 }
4599
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004600 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4601 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4602 }
4603
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004605 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4606 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004607 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004608 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4609 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004610 displayId, policyFlags, motionEvent.getAction(),
4611 motionEvent.getActionButton(), flags,
4612 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004613 motionEvent.getButtonState(),
4614 motionEvent.getClassification(),
4615 motionEvent.getEdgeFlags(),
4616 motionEvent.getXPrecision(),
4617 motionEvent.getYPrecision(),
4618 motionEvent.getRawXCursorPosition(),
4619 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004620 motionEvent.getDownTime(),
4621 motionEvent.getPointerCount(),
4622 motionEvent.getPointerProperties(),
4623 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004624 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004625 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004626 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004627 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004628 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004629 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004630 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4631 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004632 displayId, policyFlags,
4633 motionEvent.getAction(),
4634 motionEvent.getActionButton(), flags,
4635 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004636 motionEvent.getButtonState(),
4637 motionEvent.getClassification(),
4638 motionEvent.getEdgeFlags(),
4639 motionEvent.getXPrecision(),
4640 motionEvent.getYPrecision(),
4641 motionEvent.getRawXCursorPosition(),
4642 motionEvent.getRawYCursorPosition(),
4643 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004644 motionEvent.getPointerCount(),
4645 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004646 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004647 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4648 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004649 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 }
4651 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004654 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004655 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004656 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 }
4658
Prabir Pradhan5735a322022-04-11 17:23:34 +00004659 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004660 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 injectionState->injectionIsAsync = true;
4662 }
4663
4664 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004665 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666
4667 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004668 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004669 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004670 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004671 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004672 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004673 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 }
4675
4676 mLock.unlock();
4677
4678 if (needWake) {
4679 mLooper->wake();
4680 }
4681
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004682 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004684 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004686 if (syncMode == InputEventInjectionSync::NONE) {
4687 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 } else {
4689 for (;;) {
4690 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 break;
4693 }
4694
4695 nsecs_t remainingTimeout = endTime - now();
4696 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004697 if (DEBUG_INJECTION) {
4698 ALOGD("injectInputEvent - Timed out waiting for injection result "
4699 "to become available.");
4700 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004701 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 break;
4703 }
4704
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004705 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 }
4707
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004708 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4709 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004711 if (DEBUG_INJECTION) {
4712 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4713 injectionState->pendingForegroundDispatches);
4714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 nsecs_t remainingTimeout = endTime - now();
4716 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004717 if (DEBUG_INJECTION) {
4718 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4719 "dispatches to finish.");
4720 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004721 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 break;
4723 }
4724
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004725 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 }
4727 }
4728 }
4729
4730 injectionState->release();
4731 } // release lock
4732
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004733 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004734 LOG(INFO) << "injectInputEvent - Finished with result "
4735 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737
4738 return injectionResult;
4739}
4740
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004741std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004742 std::array<uint8_t, 32> calculatedHmac;
4743 std::unique_ptr<VerifiedInputEvent> result;
4744 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004745 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004746 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4747 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4748 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004749 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004750 break;
4751 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004752 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004753 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4754 VerifiedMotionEvent verifiedMotionEvent =
4755 verifiedMotionEventFromMotionEvent(motionEvent);
4756 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004757 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004758 break;
4759 }
4760 default: {
4761 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4762 return nullptr;
4763 }
4764 }
4765 if (calculatedHmac == INVALID_HMAC) {
4766 return nullptr;
4767 }
tyiu1573a672023-02-21 22:38:32 +00004768 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004769 return nullptr;
4770 }
4771 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004772}
4773
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004774void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004775 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004776 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004778 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004779 LOG(INFO) << "Setting input event injection result to "
4780 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004783 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 // Log the outcome since the injector did not wait for the injection result.
4785 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004786 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 ALOGV("Asynchronous input event injection succeeded.");
4788 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004789 case InputEventInjectionResult::TARGET_MISMATCH:
4790 ALOGV("Asynchronous input event injection target mismatch.");
4791 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004792 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004793 ALOGW("Asynchronous input event injection failed.");
4794 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004795 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004796 ALOGW("Asynchronous input event injection timed out.");
4797 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004798 case InputEventInjectionResult::PENDING:
4799 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4800 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802 }
4803
4804 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004805 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 }
4807}
4808
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004809void InputDispatcher::transformMotionEntryForInjectionLocked(
4810 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004811 // Input injection works in the logical display coordinate space, but the input pipeline works
4812 // display space, so we need to transform the injected events accordingly.
4813 const auto it = mDisplayInfos.find(entry.displayId);
4814 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004815 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004816
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004817 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4818 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4819 const vec2 cursor =
4820 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4821 {entry.xCursorPosition, entry.yCursorPosition});
4822 entry.xCursorPosition = cursor.x;
4823 entry.yCursorPosition = cursor.y;
4824 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004825 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004826 entry.pointerCoords[i] =
4827 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4828 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004829 }
4830}
4831
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004832void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4833 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 if (injectionState) {
4835 injectionState->pendingForegroundDispatches += 1;
4836 }
4837}
4838
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004839void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4840 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 if (injectionState) {
4842 injectionState->pendingForegroundDispatches -= 1;
4843
4844 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004845 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 }
4847 }
4848}
4849
chaviw98318de2021-05-19 16:45:23 -05004850const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004851 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004852 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004853 auto it = mWindowHandlesByDisplay.find(displayId);
4854 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004855}
4856
chaviw98318de2021-05-19 16:45:23 -05004857sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004858 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004859 if (windowHandleToken == nullptr) {
4860 return nullptr;
4861 }
4862
Arthur Hungb92218b2018-08-14 12:00:21 +08004863 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004864 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4865 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004866 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004867 return windowHandle;
4868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 }
4870 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004871 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872}
4873
chaviw98318de2021-05-19 16:45:23 -05004874sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4875 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004876 if (windowHandleToken == nullptr) {
4877 return nullptr;
4878 }
4879
chaviw98318de2021-05-19 16:45:23 -05004880 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004881 if (windowHandle->getToken() == windowHandleToken) {
4882 return windowHandle;
4883 }
4884 }
4885 return nullptr;
4886}
4887
chaviw98318de2021-05-19 16:45:23 -05004888sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4889 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004890 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004891 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4892 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004893 if (handle->getId() == windowHandle->getId() &&
4894 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004895 if (windowHandle->getInfo()->displayId != it.first) {
4896 ALOGE("Found window %s in display %" PRId32
4897 ", but it should belong to display %" PRId32,
4898 windowHandle->getName().c_str(), it.first,
4899 windowHandle->getInfo()->displayId);
4900 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004901 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 }
4904 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004905 return nullptr;
4906}
4907
chaviw98318de2021-05-19 16:45:23 -05004908sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004909 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4910 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911}
4912
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004913ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4914 auto displayInfoIt = mDisplayInfos.find(displayId);
4915 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4916 : kIdentityTransform;
4917}
4918
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004919bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4920 const MotionEntry& motionEntry) const {
4921 const WindowInfo& info = *window->getInfo();
4922
4923 // Skip spy window targets that are not valid for targeted injection.
4924 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004925 return false;
4926 }
4927
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004928 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4929 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4930 return false;
4931 }
4932
4933 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4934 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4935 window->getName().c_str());
4936 return false;
4937 }
4938
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004939 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004940 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004941 ALOGW("Not sending touch to %s because there's no corresponding connection",
4942 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004943 return false;
4944 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004945
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004946 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004947 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004948 return false;
4949 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004950
4951 // Drop events that can't be trusted due to occlusion
4952 const auto [x, y] = resolveTouchedPosition(motionEntry);
4953 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4954 if (!isTouchTrustedLocked(occlusionInfo)) {
4955 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004956 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004957 for (const auto& log : occlusionInfo.debugInfo) {
4958 ALOGD("%s", log.c_str());
4959 }
4960 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004961 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4962 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004963 return false;
4964 }
4965
4966 // Drop touch events if requested by input feature
4967 if (shouldDropInput(motionEntry, window)) {
4968 return false;
4969 }
4970
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004971 return true;
4972}
4973
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004974std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4975 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004976 auto connectionIt = mConnectionsByToken.find(token);
4977 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004978 return nullptr;
4979 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004980 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004981}
4982
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004983void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004984 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4985 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004986 // Remove all handles on a display if there are no windows left.
4987 mWindowHandlesByDisplay.erase(displayId);
4988 return;
4989 }
4990
4991 // Since we compare the pointer of input window handles across window updates, we need
4992 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004993 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4994 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4995 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004996 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004997 }
4998
chaviw98318de2021-05-19 16:45:23 -05004999 std::vector<sp<WindowInfoHandle>> newHandles;
5000 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005001 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005002 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005003 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005004 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005005 const bool canReceiveInput =
5006 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5007 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005008 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005009 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005010 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005011 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005012 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005013 }
5014
5015 if (info->displayId != displayId) {
5016 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5017 handle->getName().c_str(), displayId, info->displayId);
5018 continue;
5019 }
5020
Robert Carredd13602020-04-13 17:24:34 -07005021 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5022 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005023 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005024 oldHandle->updateFrom(handle);
5025 newHandles.push_back(oldHandle);
5026 } else {
5027 newHandles.push_back(handle);
5028 }
5029 }
5030
5031 // Insert or replace
5032 mWindowHandlesByDisplay[displayId] = newHandles;
5033}
5034
Arthur Hungb92218b2018-08-14 12:00:21 +08005035/**
5036 * Called from InputManagerService, update window handle list by displayId that can receive input.
5037 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5038 * If set an empty list, remove all handles from the specific display.
5039 * For focused handle, check if need to change and send a cancel event to previous one.
5040 * For removed handle, check if need to send a cancel event if already in touch.
5041 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005042void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005043 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005044 if (DEBUG_FOCUS) {
5045 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005046 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005047 windowList += iwh->getName() + " ";
5048 }
5049 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051
Prabir Pradhand65552b2021-10-07 11:23:50 -07005052 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005053 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005054 const WindowInfo& info = *window->getInfo();
5055
5056 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005057 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005058 if (noInputWindow && window->getToken() != nullptr) {
5059 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5060 window->getName().c_str());
5061 window->releaseChannel();
5062 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005063
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005064 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005065 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5066 !info.inputConfig.test(
5067 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005068 "%s has feature SPY, but is not a trusted overlay.",
5069 window->getName().c_str());
5070
Prabir Pradhand65552b2021-10-07 11:23:50 -07005071 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005072 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5073 !info.inputConfig.test(
5074 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005075 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5076 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005077 }
5078
Arthur Hung72d8dc32020-03-28 00:48:39 +00005079 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005080 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081
chaviw98318de2021-05-19 16:45:23 -05005082 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005083
chaviw98318de2021-05-19 16:45:23 -05005084 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005085
Vishnu Nairc519ff72021-01-21 08:23:08 -08005086 std::optional<FocusResolver::FocusChanges> changes =
5087 mFocusResolver.setInputWindows(displayId, windowHandles);
5088 if (changes) {
5089 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005092 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5093 mTouchStatesByDisplay.find(displayId);
5094 if (stateIt != mTouchStatesByDisplay.end()) {
5095 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005096 for (size_t i = 0; i < state.windows.size();) {
5097 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005098 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005099 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005100 ALOGD("Touched window was removed: %s in display %" PRId32,
5101 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005102 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005103 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005104 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5105 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005106 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005107 "touched window was removed");
5108 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005109 // Since we are about to drop the touch, cancel the events for the wallpaper as
5110 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005111 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005112 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5113 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005114 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005115 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005118 state.windows.erase(state.windows.begin() + i);
5119 } else {
5120 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 }
5122 }
arthurhungb89ccb02020-12-30 16:19:01 +08005123
arthurhung6d4bed92021-03-17 11:59:33 +08005124 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005125 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005126 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005127 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005128 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005129 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5130 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005131 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005132 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005133 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005134
Arthur Hung72d8dc32020-03-28 00:48:39 +00005135 // Release information for windows that are no longer present.
5136 // This ensures that unused input channels are released promptly.
5137 // Otherwise, they might stick around until the window handle is destroyed
5138 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005139 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005140 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005141 if (DEBUG_FOCUS) {
5142 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005143 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005144 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005145 }
chaviw291d88a2019-02-14 10:33:58 -08005146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147}
5148
5149void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005150 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005151 if (DEBUG_FOCUS) {
5152 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5153 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5154 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005155 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005156 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005157 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 } // release lock
5159
5160 // Wake up poll loop since it may need to make new input dispatching choices.
5161 mLooper->wake();
5162}
5163
Vishnu Nair599f1412021-06-21 10:39:58 -07005164void InputDispatcher::setFocusedApplicationLocked(
5165 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5166 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5167 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5168
5169 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5170 return; // This application is already focused. No need to wake up or change anything.
5171 }
5172
5173 // Set the new application handle.
5174 if (inputApplicationHandle != nullptr) {
5175 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5176 } else {
5177 mFocusedApplicationHandlesByDisplay.erase(displayId);
5178 }
5179
5180 // No matter what the old focused application was, stop waiting on it because it is
5181 // no longer focused.
5182 resetNoFocusedWindowTimeoutLocked();
5183}
5184
Tiger Huang721e26f2018-07-24 22:26:19 +08005185/**
5186 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5187 * the display not specified.
5188 *
5189 * We track any unreleased events for each window. If a window loses the ability to receive the
5190 * released event, we will send a cancel event to it. So when the focused display is changed, we
5191 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5192 * display. The display-specified events won't be affected.
5193 */
5194void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005195 if (DEBUG_FOCUS) {
5196 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5197 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005198 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005199 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005200
5201 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005202 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005203 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005204 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005205 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005206 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005207 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005208 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005209 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005210 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005211 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005212 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5213 }
5214 }
5215 mFocusedDisplayId = displayId;
5216
Chris Ye3c2d6f52020-08-09 10:39:48 -07005217 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005218 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005219 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005220
Vishnu Nairad321cd2020-08-20 16:40:21 -07005221 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005222 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005223 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005224 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005225 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005226 }
5227 }
5228 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005229 } // release lock
5230
5231 // Wake up poll loop since it may need to make new input dispatching choices.
5232 mLooper->wake();
5233}
5234
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005236 if (DEBUG_FOCUS) {
5237 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239
5240 bool changed;
5241 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005242 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243
5244 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5245 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005246 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 }
5248
5249 if (mDispatchEnabled && !enabled) {
5250 resetAndDropEverythingLocked("dispatcher is being disabled");
5251 }
5252
5253 mDispatchEnabled = enabled;
5254 mDispatchFrozen = frozen;
5255 changed = true;
5256 } else {
5257 changed = false;
5258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 } // release lock
5260
5261 if (changed) {
5262 // Wake up poll loop since it may need to make new input dispatching choices.
5263 mLooper->wake();
5264 }
5265}
5266
5267void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005268 if (DEBUG_FOCUS) {
5269 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271
5272 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005273 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274
5275 if (mInputFilterEnabled == enabled) {
5276 return;
5277 }
5278
5279 mInputFilterEnabled = enabled;
5280 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5281 } // release lock
5282
5283 // Wake up poll loop since there might be work to do to drop everything.
5284 mLooper->wake();
5285}
5286
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005287bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005288 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005289 bool needWake = false;
5290 {
5291 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005292 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005293 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005294 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005295 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5296 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005297 mTouchModePerDisplay.count(displayId) == 0
5298 ? "not set"
5299 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5300
Antonio Kantek15beb512022-06-13 22:35:41 +00005301 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5302 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005303 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005304 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005305 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005306 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5307 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005308 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005309 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005310 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005311 return false;
5312 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005313 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005314 mTouchModePerDisplay[displayId] = inTouchMode;
5315 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5316 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005317 needWake = enqueueInboundEventLocked(std::move(entry));
5318 } // release lock
5319
5320 if (needWake) {
5321 mLooper->wake();
5322 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005323 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005324}
5325
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005326bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005327 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5328 if (focusedToken == nullptr) {
5329 return false;
5330 }
5331 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5332 return isWindowOwnedBy(windowHandle, pid, uid);
5333}
5334
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005335bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005336 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5337 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5338 const sp<WindowInfoHandle> windowHandle =
5339 getWindowHandleLocked(connectionToken);
5340 return isWindowOwnedBy(windowHandle, pid, uid);
5341 }) != mInteractionConnectionTokens.end();
5342}
5343
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005344void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5345 if (opacity < 0 || opacity > 1) {
5346 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5347 return;
5348 }
5349
5350 std::scoped_lock lock(mLock);
5351 mMaximumObscuringOpacityForTouch = opacity;
5352}
5353
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005354std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5355InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005356 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5357 for (TouchedWindow& w : state.windows) {
5358 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005359 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005360 }
5361 }
5362 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005363 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005364}
5365
arthurhungb89ccb02020-12-30 16:19:01 +08005366bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5367 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005368 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005369 if (DEBUG_FOCUS) {
5370 ALOGD("Trivial transfer to same window.");
5371 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005372 return true;
5373 }
5374
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377
Arthur Hungabbb9d82021-09-01 14:52:30 +00005378 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005379 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005380
Arthur Hungabbb9d82021-09-01 14:52:30 +00005381 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005382 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005383 return false;
5384 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005385 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5386 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005387 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5388 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005389 return false;
5390 }
5391 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005392
Arthur Hungabbb9d82021-09-01 14:52:30 +00005393 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5394 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005395 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005396 return false;
5397 }
5398
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005399 if (DEBUG_FOCUS) {
5400 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005401 touchedWindow->windowHandle->getName().c_str(),
5402 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 }
5404
Arthur Hungabbb9d82021-09-01 14:52:30 +00005405 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005406 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005407 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005408 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005409 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
Arthur Hungabbb9d82021-09-01 14:52:30 +00005411 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005412 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005413 ftl::Flags<InputTarget::Flags> newTargetFlags =
5414 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005415 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005416 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005417 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005418 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5419 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420
Arthur Hungabbb9d82021-09-01 14:52:30 +00005421 // Store the dragging window.
5422 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005423 if (pointerIds.count() != 1) {
5424 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5425 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005426 return false;
5427 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005428 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005429 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005430 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 }
5432
Arthur Hungabbb9d82021-09-01 14:52:30 +00005433 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005434 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5435 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005436 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005437 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005438 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5439 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005441 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5442 newTargetFlags);
5443
5444 // Check if the wallpaper window should deliver the corresponding event.
5445 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005446 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 } // release lock
5449
5450 // Wake up poll loop since it may need to make new input dispatching choices.
5451 mLooper->wake();
5452 return true;
5453}
5454
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005455/**
5456 * Get the touched foreground window on the given display.
5457 * Return null if there are no windows touched on that display, or if more than one foreground
5458 * window is being touched.
5459 */
5460sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5461 auto stateIt = mTouchStatesByDisplay.find(displayId);
5462 if (stateIt == mTouchStatesByDisplay.end()) {
5463 ALOGI("No touch state on display %" PRId32, displayId);
5464 return nullptr;
5465 }
5466
5467 const TouchState& state = stateIt->second;
5468 sp<WindowInfoHandle> touchedForegroundWindow;
5469 // If multiple foreground windows are touched, return nullptr
5470 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005471 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005472 if (touchedForegroundWindow != nullptr) {
5473 ALOGI("Two or more foreground windows: %s and %s",
5474 touchedForegroundWindow->getName().c_str(),
5475 window.windowHandle->getName().c_str());
5476 return nullptr;
5477 }
5478 touchedForegroundWindow = window.windowHandle;
5479 }
5480 }
5481 return touchedForegroundWindow;
5482}
5483
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005484// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005485bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005486 sp<IBinder> fromToken;
5487 { // acquire lock
5488 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005489 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005490 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005491 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5492 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005493 return false;
5494 }
5495
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005496 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5497 if (from == nullptr) {
5498 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5499 return false;
5500 }
5501
5502 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005503 } // release lock
5504
5505 return transferTouchFocus(fromToken, destChannelToken);
5506}
5507
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005509 if (DEBUG_FOCUS) {
5510 ALOGD("Resetting and dropping all events (%s).", reason);
5511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512
Michael Wrightfb04fd52022-11-24 22:31:11 +00005513 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 synthesizeCancelationEventsForAllConnectionsLocked(options);
5515
5516 resetKeyRepeatLocked();
5517 releasePendingEventLocked();
5518 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005519 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005521 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005522 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523}
5524
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005525void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005526 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 dumpDispatchStateLocked(dump);
5528
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005529 std::istringstream stream(dump);
5530 std::string line;
5531
5532 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005533 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 }
5535}
5536
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005537std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005538 std::string dump;
5539
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005540 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5541 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005542
5543 std::string windowName = "None";
5544 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005545 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005546 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5547 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5548 : "token has capture without window";
5549 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005550 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005551
5552 return dump;
5553}
5554
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005555void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005556 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5557 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5558 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005559 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560
Tiger Huang721e26f2018-07-24 22:26:19 +08005561 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5562 dump += StringPrintf(INDENT "FocusedApplications:\n");
5563 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5564 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005565 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005566 const std::chrono::duration timeout =
5567 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005568 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005569 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005570 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005573 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005575
Vishnu Nairc519ff72021-01-21 08:23:08 -08005576 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005577 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005579 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005580 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005581 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005582 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5583 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 }
5585 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005586 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 }
5588
arthurhung6d4bed92021-03-17 11:59:33 +08005589 if (mDragState) {
5590 dump += StringPrintf(INDENT "DragState:\n");
5591 mDragState->dump(dump, INDENT2);
5592 }
5593
Arthur Hungb92218b2018-08-14 12:00:21 +08005594 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005595 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5596 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5597 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5598 const auto& displayInfo = it->second;
5599 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5600 displayInfo.logicalHeight);
5601 displayInfo.transform.dump(dump, "transform", INDENT4);
5602 } else {
5603 dump += INDENT2 "No DisplayInfo found!\n";
5604 }
5605
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005606 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005607 dump += INDENT2 "Windows:\n";
5608 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005609 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5610 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005612 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005613 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005614 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005615 "applicationInfo.name=%s, "
5616 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005617 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005618 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005619 windowInfo->displayId,
5620 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005621 windowInfo->alpha, windowInfo->frame.left,
5622 windowInfo->frame.top, windowInfo->frame.right,
5623 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005624 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005625 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005626 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005627 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005628 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005629 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005630 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005631 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005632 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005633 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005634 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005635 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005636 }
5637 } else {
5638 dump += INDENT2 "Windows: <none>\n";
5639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005642 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 }
5644
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005645 if (!mGlobalMonitorsByDisplay.empty()) {
5646 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5647 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005648 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005651 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 }
5653
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005654 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655
5656 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005657 if (!mRecentQueue.empty()) {
5658 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005659 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005660 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005661 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005662 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663 }
5664 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005665 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 }
5667
5668 // Dump event currently being dispatched.
5669 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005670 dump += INDENT "PendingEvent:\n";
5671 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005672 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005673 dump += StringPrintf(", age=%" PRId64 "ms\n",
5674 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005676 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 }
5678
5679 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005680 if (!mInboundQueue.empty()) {
5681 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005682 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005684 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005685 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 }
5687 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005688 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 }
5690
Prabir Pradhancef936d2021-07-21 16:17:52 +00005691 if (!mCommandQueue.empty()) {
5692 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5693 } else {
5694 dump += INDENT "CommandQueue: <empty>\n";
5695 }
5696
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005697 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005698 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005699 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005700 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005701 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005702 connection->inputChannel->getFd().get(),
5703 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005704 connection->getWindowName().c_str(),
5705 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005706 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005708 if (!connection->outboundQueue.empty()) {
5709 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5710 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005711 dump += dumpQueue(connection->outboundQueue, currentTime);
5712
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005714 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005717 if (!connection->waitQueue.empty()) {
5718 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5719 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005720 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005724 std::stringstream inputStateDump;
5725 inputStateDump << connection->inputState;
5726 if (!isEmpty(inputStateDump)) {
5727 dump += INDENT3 "InputState: ";
5728 dump += inputStateDump.str() + "\n";
5729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
5731 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005732 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 }
5734
5735 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005736 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5737 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005739 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741
Antonio Kantek15beb512022-06-13 22:35:41 +00005742 if (!mTouchModePerDisplay.empty()) {
5743 dump += INDENT "TouchModePerDisplay:\n";
5744 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5745 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5746 std::to_string(touchMode).c_str());
5747 }
5748 } else {
5749 dump += INDENT "TouchModePerDisplay: <none>\n";
5750 }
5751
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005752 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005753 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5754 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5755 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005756 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005757 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758}
5759
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005760void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005761 const size_t numMonitors = monitors.size();
5762 for (size_t i = 0; i < numMonitors; i++) {
5763 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005764 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005765 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5766 dump += "\n";
5767 }
5768}
5769
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005770class LooperEventCallback : public LooperCallback {
5771public:
5772 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5773 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5774
5775private:
5776 std::function<int(int events)> mCallback;
5777};
5778
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005779Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005780 if (DEBUG_CHANNEL_CREATION) {
5781 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005784 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005785 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005786 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005787
5788 if (result) {
5789 return base::Error(result) << "Failed to open input channel pair with name " << name;
5790 }
5791
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005793 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005794 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005795 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005796 std::shared_ptr<Connection> connection =
5797 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5798 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005800 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5801 ALOGE("Created a new connection, but the token %p is already known", token.get());
5802 }
5803 mConnectionsByToken.emplace(token, connection);
5804
5805 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5806 this, std::placeholders::_1, token);
5807
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005808 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5809 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 } // release lock
5811
5812 // Wake the looper because some connections have changed.
5813 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005814 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815}
5816
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005817Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005818 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005819 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005820 std::shared_ptr<InputChannel> serverChannel;
5821 std::unique_ptr<InputChannel> clientChannel;
5822 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5823 if (result) {
5824 return base::Error(result) << "Failed to open input channel pair with name " << name;
5825 }
5826
Michael Wright3dd60e22019-03-27 22:06:44 +00005827 { // acquire lock
5828 std::scoped_lock _l(mLock);
5829
5830 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005831 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5832 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005833 }
5834
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005835 std::shared_ptr<Connection> connection =
5836 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005837 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005838 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839
5840 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5841 ALOGE("Created a new connection, but the token %p is already known", token.get());
5842 }
5843 mConnectionsByToken.emplace(token, connection);
5844 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5845 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005846
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005847 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005848
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005849 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5850 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005851 }
Garfield Tan15601662020-09-22 15:32:38 -07005852
Michael Wright3dd60e22019-03-27 22:06:44 +00005853 // Wake the looper because some connections have changed.
5854 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005855 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005856}
5857
Garfield Tan15601662020-09-22 15:32:38 -07005858status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005860 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861
Harry Cutts33476232023-01-30 19:57:29 +00005862 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 if (status) {
5864 return status;
5865 }
5866 } // release lock
5867
5868 // Wake the poll loop because removing the connection may have changed the current
5869 // synchronization state.
5870 mLooper->wake();
5871 return OK;
5872}
5873
Garfield Tan15601662020-09-22 15:32:38 -07005874status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5875 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005876 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005877 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005878 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 return BAD_VALUE;
5880 }
5881
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005882 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005883
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005885 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 }
5887
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005888 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889
5890 nsecs_t currentTime = now();
5891 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5892
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005893 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 return OK;
5895}
5896
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005897void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005898 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5899 auto& [displayId, monitors] = *it;
5900 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5901 return monitor.inputChannel->getConnectionToken() == connectionToken;
5902 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005903
Michael Wright3dd60e22019-03-27 22:06:44 +00005904 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005905 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005906 } else {
5907 ++it;
5908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909 }
5910}
5911
Michael Wright3dd60e22019-03-27 22:06:44 +00005912status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005913 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005914 return pilferPointersLocked(token);
5915}
Michael Wright3dd60e22019-03-27 22:06:44 +00005916
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005917status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005918 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5919 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005920 LOG(WARNING)
5921 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005922 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005923 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005924
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005925 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005926 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005927 LOG(WARNING)
5928 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5929 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005930 return BAD_VALUE;
5931 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005932 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5933 if (deviceIds.size() != 1) {
5934 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5935 << " in window: " << windowPtr->dump();
5936 return BAD_VALUE;
5937 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005938
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005939 for (const DeviceId deviceId : deviceIds) {
5940 TouchState& state = *statePtr;
5941 TouchedWindow& window = *windowPtr;
5942 // Send cancel events to all the input channels we're stealing from.
5943 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5944 "input channel stole pointer stream");
5945 options.deviceId = deviceId;
5946 options.displayId = displayId;
5947 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5948 options.pointerIds = pointerIds;
5949 std::string canceledWindows;
5950 for (const TouchedWindow& w : state.windows) {
5951 const std::shared_ptr<InputChannel> channel =
5952 getInputChannelLocked(w.windowHandle->getToken());
5953 if (channel != nullptr && channel->getConnectionToken() != token) {
5954 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5955 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5956 canceledWindows += channel->getName();
5957 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005958 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005959 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5960 LOG(INFO) << "Channel " << requestingChannel->getName()
5961 << " is stealing input gesture for device " << deviceId << " from "
5962 << canceledWindows;
5963
5964 // Prevent the gesture from being sent to any other windows.
5965 // This only blocks relevant pointers to be sent to other windows
5966 window.addPilferingPointers(deviceId, pointerIds);
5967
5968 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005969 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005970 return OK;
5971}
5972
Prabir Pradhan99987712020-11-10 18:43:05 -08005973void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5974 { // acquire lock
5975 std::scoped_lock _l(mLock);
5976 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005977 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005978 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5979 windowHandle != nullptr ? windowHandle->getName().c_str()
5980 : "token without window");
5981 }
5982
Vishnu Nairc519ff72021-01-21 08:23:08 -08005983 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005984 if (focusedToken != windowToken) {
5985 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5986 enabled ? "enable" : "disable");
5987 return;
5988 }
5989
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005990 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005991 ALOGW("Ignoring request to %s Pointer Capture: "
5992 "window has %s requested pointer capture.",
5993 enabled ? "enable" : "disable", enabled ? "already" : "not");
5994 return;
5995 }
5996
Christine Franksb768bb42021-11-29 12:11:31 -08005997 if (enabled) {
5998 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5999 mIneligibleDisplaysForPointerCapture.end(),
6000 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6001 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6002 return;
6003 }
6004 }
6005
Prabir Pradhan99987712020-11-10 18:43:05 -08006006 setPointerCaptureLocked(enabled);
6007 } // release lock
6008
6009 // Wake the thread to process command entries.
6010 mLooper->wake();
6011}
6012
Christine Franksb768bb42021-11-29 12:11:31 -08006013void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6014 { // acquire lock
6015 std::scoped_lock _l(mLock);
6016 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6017 if (!isEligible) {
6018 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6019 }
6020 } // release lock
6021}
6022
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006023std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006024 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006025 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006026 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006027 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006028 }
6029 }
6030 }
6031 return std::nullopt;
6032}
6033
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006034std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6035 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006036 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006037 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006038 }
6039
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006040 for (const auto& [token, connection] : mConnectionsByToken) {
6041 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006042 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043 }
6044 }
Robert Carr4e670e52018-08-15 13:26:12 -07006045
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006046 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047}
6048
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006049std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006050 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006051 if (connection == nullptr) {
6052 return "<nullptr>";
6053 }
6054 return connection->getInputChannelName();
6055}
6056
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006057void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006058 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006059 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006060}
6061
Prabir Pradhancef936d2021-07-21 16:17:52 +00006062void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006063 const std::shared_ptr<Connection>& connection,
6064 uint32_t seq, bool handled,
6065 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006066 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006067 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006068
6069 { // Start critical section
6070 auto dispatchEntryIt =
6071 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6072 [seq](auto& e) { return e->seq == seq; });
6073 if (dispatchEntryIt == connection->waitQueue.end()) {
6074 return;
6075 }
6076
6077 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6078
6079 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6080 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6081 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6082 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6083 }
6084 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6085 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6086 connection->inputChannel->getConnectionToken(),
6087 dispatchEntry.deliveryTime, consumeTime, finishTime);
6088 }
6089
6090 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6091 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6092 restartEvent =
6093 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6094 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6095 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6096 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6097 motionEntry, handled);
6098 } else {
6099 restartEvent = false;
6100 }
6101 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006102
6103 // Dequeue the event and start the next cycle.
6104 // Because the lock might have been released, it is possible that the
6105 // contents of the wait queue to have been drained, so we need to double-check
6106 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006107 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6108 [seq](auto& e) { return e->seq == seq; });
6109 if (entryIt != connection->waitQueue.end()) {
6110 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6111 connection->waitQueue.erase(entryIt);
6112
Prabir Pradhancef936d2021-07-21 16:17:52 +00006113 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6114 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6115 if (!connection->responsive) {
6116 connection->responsive = isConnectionResponsive(*connection);
6117 if (connection->responsive) {
6118 // The connection was unresponsive, and now it's responsive.
6119 processConnectionResponsiveLocked(*connection);
6120 }
6121 }
6122 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006123 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006124 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006125 traceOutboundQueueLength(*connection);
6126 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006127 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006128 }
6129 }
6130
6131 // Start the next dispatch cycle for this connection.
6132 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133}
6134
Prabir Pradhancef936d2021-07-21 16:17:52 +00006135void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6136 const sp<IBinder>& newToken) {
6137 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6138 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006139 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006140 };
6141 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006142}
6143
Prabir Pradhancef936d2021-07-21 16:17:52 +00006144void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6145 auto command = [this, token, x, y]() REQUIRES(mLock) {
6146 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006147 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006148 };
6149 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006150}
6151
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006152void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006153 if (connection == nullptr) {
6154 LOG_ALWAYS_FATAL("Caller must check for nullness");
6155 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006156 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6157 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006158 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006159 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006160 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006161 return;
6162 }
6163 /**
6164 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6165 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6166 * has changed. This could cause newer entries to time out before the already dispatched
6167 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6168 * processes the events linearly. So providing information about the oldest entry seems to be
6169 * most useful.
6170 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006171 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6172 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006173 std::string reason =
6174 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006175 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006176 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006177 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006178 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006179 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006180
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006181 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6182
6183 // Stop waking up for events on this connection, it is already unresponsive
6184 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006185}
6186
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006187void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6188 std::string reason =
6189 StringPrintf("%s does not have a focused window", application->getName().c_str());
6190 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006191
Yabin Cui8eb9c552023-06-08 18:05:07 +00006192 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006193 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006194 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006195 };
6196 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006197}
6198
chaviw98318de2021-05-19 16:45:23 -05006199void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006200 const std::string& reason) {
6201 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6202 updateLastAnrStateLocked(windowLabel, reason);
6203}
6204
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006205void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6206 const std::string& reason) {
6207 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006208 updateLastAnrStateLocked(windowLabel, reason);
6209}
6210
6211void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6212 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006214 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215 struct tm tm;
6216 localtime_r(&t, &tm);
6217 char timestr[64];
6218 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006219 mLastAnrState.clear();
6220 mLastAnrState += INDENT "ANR:\n";
6221 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006222 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6223 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006224 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225}
6226
Prabir Pradhancef936d2021-07-21 16:17:52 +00006227void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6228 KeyEntry& entry) {
6229 const KeyEvent event = createKeyEvent(entry);
6230 nsecs_t delay = 0;
6231 { // release lock
6232 scoped_unlock unlock(mLock);
6233 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006234 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006235 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6236 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6237 std::to_string(t.duration().count()).c_str());
6238 }
6239 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240
6241 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006242 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006243 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006244 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006246 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006247 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249}
6250
Prabir Pradhancef936d2021-07-21 16:17:52 +00006251void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006252 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006253 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006254 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006255 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006256 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006257 };
6258 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006259}
6260
Prabir Pradhanedd96402022-02-15 01:46:16 -08006261void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006262 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006263 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006265 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006266 };
6267 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006268}
6269
6270/**
6271 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6272 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6273 * command entry to the command queue.
6274 */
6275void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6276 std::string reason) {
6277 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006278 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006279 if (connection.monitor) {
6280 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6281 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006282 pid = findMonitorPidByTokenLocked(connectionToken);
6283 } else {
6284 // The connection is a window
6285 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6286 reason.c_str());
6287 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6288 if (handle != nullptr) {
6289 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006290 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006291 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006292 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006293}
6294
6295/**
6296 * Tell the policy that a connection has become responsive so that it can stop ANR.
6297 */
6298void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6299 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006300 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006301 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006302 pid = findMonitorPidByTokenLocked(connectionToken);
6303 } else {
6304 // The connection is a window
6305 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6306 if (handle != nullptr) {
6307 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006308 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006309 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006310 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006311}
6312
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006313bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006314 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006315 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006316 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006317 if (!handled) {
6318 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006319 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006320 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006321 return false;
6322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006324 // Get the fallback key state.
6325 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006326 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006327 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006328 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006329 connection->inputState.removeFallbackKey(originalKeyCode);
6330 }
6331
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006332 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006333 // If the application handles the original key for which we previously
6334 // generated a fallback or if the window is not a foreground window,
6335 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006336 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006337 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006338 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6339 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6340 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6341 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6342 keyEntry.policyFlags);
6343 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006344 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006345 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346
6347 mLock.unlock();
6348
Prabir Pradhana41d2442023-04-20 21:30:40 +00006349 if (const auto unhandledKeyFallback =
6350 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6351 event, keyEntry.policyFlags);
6352 unhandledKeyFallback) {
6353 event = *unhandledKeyFallback;
6354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006355
6356 mLock.lock();
6357
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006358 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006359 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006360 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006361 "application handled the original non-fallback key "
6362 "or is no longer a foreground target, "
6363 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006364 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006367 connection->inputState.removeFallbackKey(originalKeyCode);
6368 }
6369 } else {
6370 // If the application did not handle a non-fallback key, first check
6371 // that we are in a good state to perform unhandled key event processing
6372 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006373 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006374 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006375 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6376 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6377 "since this is not an initial down. "
6378 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6379 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6380 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006381 return false;
6382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006384 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006385 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6386 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6387 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6388 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6389 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006390 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006391
6392 mLock.unlock();
6393
Prabir Pradhana41d2442023-04-20 21:30:40 +00006394 bool fallback = false;
6395 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6396 event, keyEntry.policyFlags);
6397 fb) {
6398 fallback = true;
6399 event = *fb;
6400 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006401
6402 mLock.lock();
6403
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006404 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006405 connection->inputState.removeFallbackKey(originalKeyCode);
6406 return false;
6407 }
6408
6409 // Latch the fallback keycode for this key on an initial down.
6410 // The fallback keycode cannot change at any other point in the lifecycle.
6411 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006413 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006415 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006416 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006417 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006418 }
6419
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006420 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006421
6422 // Cancel the fallback key if the policy decides not to send it anymore.
6423 // We will continue to dispatch the key to the policy but we will no
6424 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006425 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6426 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006427 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6428 if (fallback) {
6429 ALOGD("Unhandled key event: Policy requested to send key %d"
6430 "as a fallback for %d, but on the DOWN it had requested "
6431 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006432 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006433 } else {
6434 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6435 "but on the DOWN it had requested to send %d. "
6436 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006437 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006438 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440
Michael Wrightfb04fd52022-11-24 22:31:11 +00006441 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006443 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006444 synthesizeCancelationEventsForConnectionLocked(connection, options);
6445
6446 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006447 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006448 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006449 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450 }
6451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006452
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006453 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6454 {
6455 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006457 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006458 for (const auto& [key, value] : fallbackKeys) {
6459 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006460 }
6461 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6462 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006465
6466 if (fallback) {
6467 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006468 keyEntry.eventTime = event.getEventTime();
6469 keyEntry.deviceId = event.getDeviceId();
6470 keyEntry.source = event.getSource();
6471 keyEntry.displayId = event.getDisplayId();
6472 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006474 keyEntry.scanCode = event.getScanCode();
6475 keyEntry.metaState = event.getMetaState();
6476 keyEntry.repeatCount = event.getRepeatCount();
6477 keyEntry.downTime = event.getDownTime();
6478 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006480 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6481 ALOGD("Unhandled key event: Dispatching fallback key. "
6482 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006483 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006484 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 return true; // restart the event
6486 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006487 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6488 ALOGD("Unhandled key event: No fallback key.");
6489 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006490
6491 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006492 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493 }
6494 }
6495 return false;
6496}
6497
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006498bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006499 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006500 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 return false;
6502}
6503
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504void InputDispatcher::traceInboundQueueLengthLocked() {
6505 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006506 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507 }
6508}
6509
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006510void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511 if (ATRACE_ENABLED()) {
6512 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006513 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6514 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006515 }
6516}
6517
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006518void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006519 if (ATRACE_ENABLED()) {
6520 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006521 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6522 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006523 }
6524}
6525
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006526void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006527 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006528
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006529 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530 dumpDispatchStateLocked(dump);
6531
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006532 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006533 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006534 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535 }
6536}
6537
6538void InputDispatcher::monitor() {
6539 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006540 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006542 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543}
6544
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006545/**
6546 * Wake up the dispatcher and wait until it processes all events and commands.
6547 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6548 * this method can be safely called from any thread, as long as you've ensured that
6549 * the work you are interested in completing has already been queued.
6550 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006551bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006552 /**
6553 * Timeout should represent the longest possible time that a device might spend processing
6554 * events and commands.
6555 */
6556 constexpr std::chrono::duration TIMEOUT = 100ms;
6557 std::unique_lock lock(mLock);
6558 mLooper->wake();
6559 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6560 return result == std::cv_status::no_timeout;
6561}
6562
Vishnu Naire798b472020-07-23 13:52:21 -07006563/**
6564 * Sets focus to the window identified by the token. This must be called
6565 * after updating any input window handles.
6566 *
6567 * Params:
6568 * request.token - input channel token used to identify the window that should gain focus.
6569 * request.focusedToken - the token that the caller expects currently to be focused. If the
6570 * specified token does not match the currently focused window, this request will be dropped.
6571 * If the specified focused token matches the currently focused window, the call will succeed.
6572 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6573 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6574 * when requesting the focus change. This determines which request gets
6575 * precedence if there is a focus change request from another source such as pointer down.
6576 */
Vishnu Nair958da932020-08-21 17:12:37 -07006577void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6578 { // acquire lock
6579 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006580 std::optional<FocusResolver::FocusChanges> changes =
6581 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6582 if (changes) {
6583 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006584 }
6585 } // release lock
6586 // Wake up poll loop since it may need to make new input dispatching choices.
6587 mLooper->wake();
6588}
6589
Vishnu Nairc519ff72021-01-21 08:23:08 -08006590void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6591 if (changes.oldFocus) {
6592 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006593 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006594 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006595 "focus left window");
6596 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006597 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006598 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006599 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006600 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006601 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006602 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006603 }
6604
Prabir Pradhan99987712020-11-10 18:43:05 -08006605 // If a window has pointer capture, then it must have focus. We need to ensure that this
6606 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6607 // If the window loses focus before it loses pointer capture, then the window can be in a state
6608 // where it has pointer capture but not focus, violating the contract. Therefore we must
6609 // dispatch the pointer capture event before the focus event. Since focus events are added to
6610 // the front of the queue (above), we add the pointer capture event to the front of the queue
6611 // after the focus events are added. This ensures the pointer capture event ends up at the
6612 // front.
6613 disablePointerCaptureForcedLocked();
6614
Vishnu Nairc519ff72021-01-21 08:23:08 -08006615 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006616 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006617 }
6618}
Vishnu Nair958da932020-08-21 17:12:37 -07006619
Prabir Pradhan99987712020-11-10 18:43:05 -08006620void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006621 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006622 return;
6623 }
6624
6625 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6626
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006627 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006628 setPointerCaptureLocked(false);
6629 }
6630
6631 if (!mWindowTokenWithPointerCapture) {
6632 // No need to send capture changes because no window has capture.
6633 return;
6634 }
6635
6636 if (mPendingEvent != nullptr) {
6637 // Move the pending event to the front of the queue. This will give the chance
6638 // for the pending event to be dropped if it is a captured event.
6639 mInboundQueue.push_front(mPendingEvent);
6640 mPendingEvent = nullptr;
6641 }
6642
6643 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006644 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006645 mInboundQueue.push_front(std::move(entry));
6646}
6647
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006648void InputDispatcher::setPointerCaptureLocked(bool enable) {
6649 mCurrentPointerCaptureRequest.enable = enable;
6650 mCurrentPointerCaptureRequest.seq++;
6651 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006652 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006653 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006654 };
6655 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006656}
6657
Vishnu Nair599f1412021-06-21 10:39:58 -07006658void InputDispatcher::displayRemoved(int32_t displayId) {
6659 { // acquire lock
6660 std::scoped_lock _l(mLock);
6661 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006662 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006663 setFocusedApplicationLocked(displayId, nullptr);
6664 // Call focus resolver to clean up stale requests. This must be called after input windows
6665 // have been removed for the removed display.
6666 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006667 // Reset pointer capture eligibility, regardless of previous state.
6668 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006669 // Remove the associated touch mode state.
6670 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006671 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006672 } // release lock
6673
6674 // Wake up poll loop since it may need to make new input dispatching choices.
6675 mLooper->wake();
6676}
6677
Patrick Williamsd828f302023-04-28 17:52:08 -05006678void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006679 // The listener sends the windows as a flattened array. Separate the windows by display for
6680 // more convenient parsing.
6681 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006682 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006683 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006684 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006685 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006686
6687 { // acquire lock
6688 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006689
6690 // Ensure that we have an entry created for all existing displays so that if a displayId has
6691 // no windows, we can tell that the windows were removed from the display.
6692 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6693 handlesPerDisplay[displayId];
6694 }
6695
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006696 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006697 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006698 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6699 }
6700
6701 for (const auto& [displayId, handles] : handlesPerDisplay) {
6702 setInputWindowsLocked(handles, displayId);
6703 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006704
6705 if (update.vsyncId < mWindowInfosVsyncId) {
6706 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6707 ", current update vsync id: %" PRId64,
6708 mWindowInfosVsyncId, update.vsyncId);
6709 }
6710 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006711 }
6712 // Wake up poll loop since it may need to make new input dispatching choices.
6713 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006714}
6715
Vishnu Nair062a8672021-09-03 16:07:44 -07006716bool InputDispatcher::shouldDropInput(
6717 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006718 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6719 (windowHandle->getInfo()->inputConfig.test(
6720 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006721 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006722 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6723 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006724 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006725 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006726 windowHandle->getInfo()->displayId);
6727 return true;
6728 }
6729 return false;
6730}
6731
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006732void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006733 const gui::WindowInfosUpdate& update) {
6734 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006735}
6736
Arthur Hungdfd528e2021-12-08 13:23:04 +00006737void InputDispatcher::cancelCurrentTouch() {
6738 {
6739 std::scoped_lock _l(mLock);
6740 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006741 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006742 "cancel current touch");
6743 synthesizeCancelationEventsForAllConnectionsLocked(options);
6744
6745 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006746 }
6747 // Wake up poll loop since there might be work to do.
6748 mLooper->wake();
6749}
6750
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006751void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6752 std::scoped_lock _l(mLock);
6753 mMonitorDispatchingTimeout = timeout;
6754}
6755
Arthur Hungc539dbb2022-12-08 07:45:36 +00006756void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6757 const sp<WindowInfoHandle>& oldWindowHandle,
6758 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006759 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006760 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006761 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6762 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006763 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6764 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6765 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6766 newWindowHandle->getInfo()->inputConfig.test(
6767 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6768 const sp<WindowInfoHandle> oldWallpaper =
6769 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6770 const sp<WindowInfoHandle> newWallpaper =
6771 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6772 if (oldWallpaper == newWallpaper) {
6773 return;
6774 }
6775
6776 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006777 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6778 addWindowTargetLocked(oldWallpaper,
6779 oldTouchedWindow.targetFlags |
6780 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006781 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6782 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006783 }
6784
6785 if (newWallpaper != nullptr) {
6786 state.addOrUpdateWindow(newWallpaper,
6787 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6788 InputTarget::Flags::WINDOW_IS_OBSCURED |
6789 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006790 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006791 }
6792}
6793
6794void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6795 ftl::Flags<InputTarget::Flags> newTargetFlags,
6796 const sp<WindowInfoHandle> fromWindowHandle,
6797 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006798 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006799 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006800 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6801 fromWindowHandle->getInfo()->inputConfig.test(
6802 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6803 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6804 toWindowHandle->getInfo()->inputConfig.test(
6805 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6806
6807 const sp<WindowInfoHandle> oldWallpaper =
6808 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6809 const sp<WindowInfoHandle> newWallpaper =
6810 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6811 if (oldWallpaper == newWallpaper) {
6812 return;
6813 }
6814
6815 if (oldWallpaper != nullptr) {
6816 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6817 "transferring touch focus to another window");
6818 state.removeWindowByToken(oldWallpaper->getToken());
6819 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6820 }
6821
6822 if (newWallpaper != nullptr) {
6823 nsecs_t downTimeInTarget = now();
6824 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6825 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6826 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6827 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006828 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6829 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006830 std::shared_ptr<Connection> wallpaperConnection =
6831 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006832 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006833 std::shared_ptr<Connection> toConnection =
6834 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006835 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6836 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6837 wallpaperFlags);
6838 }
6839 }
6840}
6841
6842sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6843 const sp<WindowInfoHandle>& windowHandle) const {
6844 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6845 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6846 bool foundWindow = false;
6847 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6848 if (!foundWindow && otherHandle != windowHandle) {
6849 continue;
6850 }
6851 if (windowHandle == otherHandle) {
6852 foundWindow = true;
6853 continue;
6854 }
6855
6856 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6857 return otherHandle;
6858 }
6859 }
6860 return nullptr;
6861}
6862
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006863void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6864 std::scoped_lock _l(mLock);
6865
6866 mConfig.keyRepeatTimeout = timeout;
6867 mConfig.keyRepeatDelay = delay;
6868}
6869
Garfield Tane84e6f92019-08-29 17:28:41 -07006870} // namespace android::inputdispatcher