blob: c8528e1a031ccdb0dd3ca5d832d508c3ff0e9e52 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056#define INDENT " "
57#define INDENT2 " "
58#define INDENT3 " "
59#define INDENT4 " "
60
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080061using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070062using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080063using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000064using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070066using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050067using android::gui::FocusRequest;
68using android::gui::TouchOcclusionMode;
69using android::gui::WindowInfo;
70using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080071using android::os::InputEventInjectionResult;
72using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000073namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080074
Siarhei Vishniakou17f12282023-11-02 13:40:29 -070075static const bool REMOVE_APP_SWITCH_DROPS = input_flags::remove_app_switch_drops();
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Prabir Pradhancef936d2021-07-21 16:17:52 +000079namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000080// Temporarily releases a held mutex for the lifetime of the instance.
81// Named to match std::scoped_lock
82class scoped_unlock {
83public:
84 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
85 ~scoped_unlock() { mMutex.lock(); }
86
87private:
88 std::mutex& mMutex;
89};
90
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// Default input dispatching timeout if there is no focused application or paused window
92// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080093const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
94 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
95 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Amount of time to allow for all pending events to be processed when an app switch
98// key is on the way. This is used to preempt input dispatch and drop input events
99// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000100constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800102const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// 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 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Antonio Kantekea47acb2021-12-23 12:41:25 -0800118// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000121constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000122
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000123const ui::Transform kIdentityTransform;
124
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000125inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126 return systemTime(SYSTEM_TIME_MONOTONIC);
127}
128
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700129bool isEmpty(const std::stringstream& ss) {
130 return ss.rdbuf()->in_avail() == 0;
131}
132
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700133inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000134 if (binder == nullptr) {
135 return "<null>";
136 }
137 return StringPrintf("%p", binder.get());
138}
139
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000140static std::string uidString(const gui::Uid& uid) {
141 return uid.toString();
142}
143
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 case AKEY_EVENT_ACTION_DOWN:
147 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700150 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 }
152}
153
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154Result<void> validateKeyEvent(int32_t action) {
155 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156}
157
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700158Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800159 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700161 case AMOTION_EVENT_ACTION_UP: {
162 if (pointerCount != 1) {
163 return Error() << "invalid pointer count " << pointerCount;
164 }
165 return {};
166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 case AMOTION_EVENT_ACTION_HOVER_ENTER:
169 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700170 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
171 if (pointerCount < 1) {
172 return Error() << "invalid pointer count " << pointerCount;
173 }
174 return {};
175 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 case AMOTION_EVENT_ACTION_CANCEL:
177 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 case AMOTION_EVENT_ACTION_POINTER_DOWN:
181 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800182 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700183 if (index < 0) {
184 return Error() << "invalid index " << index << " for "
185 << MotionEvent::actionToString(action);
186 }
187 if (index >= pointerCount) {
188 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
189 }
190 if (pointerCount <= 1) {
191 return Error() << "invalid pointer count " << pointerCount << " for "
192 << MotionEvent::actionToString(action);
193 }
194 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 }
196 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700197 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
198 if (actionButton == 0) {
199 return Error() << "action button should be nonzero for "
200 << MotionEvent::actionToString(action);
201 }
202 return {};
203 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700204 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700205 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 }
207}
208
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000209int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500210 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
211}
212
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700213Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
214 const PointerProperties* pointerProperties) {
215 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
216 if (!actionCheck.ok()) {
217 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
219 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700220 return Error() << "Motion event has invalid pointer count " << pointerCount
221 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800223 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 for (size_t i = 0; i < pointerCount; i++) {
225 int32_t id = pointerProperties[i].id;
226 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700227 return Error() << "Motion event has invalid pointer id " << id
228 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800230 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700231 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800233 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700235 return {};
236}
237
238Result<void> validateInputEvent(const InputEvent& event) {
239 switch (event.getType()) {
240 case InputEventType::KEY: {
241 const KeyEvent& key = static_cast<const KeyEvent&>(event);
242 const int32_t action = key.getAction();
243 return validateKeyEvent(action);
244 }
245 case InputEventType::MOTION: {
246 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
247 const int32_t action = motion.getAction();
248 const size_t pointerCount = motion.getPointerCount();
249 const PointerProperties* pointerProperties = motion.getPointerProperties();
250 const int32_t actionButton = motion.getActionButton();
251 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
252 }
253 default: {
254 return {};
255 }
256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257}
258
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000259std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000261 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 }
263
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000264 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 bool first = true;
266 Region::const_iterator cur = region.begin();
267 Region::const_iterator const tail = region.end();
268 while (cur != tail) {
269 if (first) {
270 first = false;
271 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800272 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800274 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275 cur++;
276 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000277 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278}
279
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000280std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
281 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500282 constexpr size_t maxEntries = 50; // max events to print
283 constexpr size_t skipBegin = maxEntries / 2;
284 const size_t skipEnd = queue.size() - maxEntries / 2;
285 // skip from maxEntries / 2 ... size() - maxEntries/2
286 // only print from 0 .. skipBegin and then from skipEnd .. size()
287
288 std::string dump;
289 for (size_t i = 0; i < queue.size(); i++) {
290 const DispatchEntry& entry = *queue[i];
291 if (i >= skipBegin && i < skipEnd) {
292 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
293 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
294 continue;
295 }
296 dump.append(INDENT4);
297 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800298 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
299 "ms",
300 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500301 ns2ms(currentTime - entry.eventEntry->eventTime));
302 if (entry.deliveryTime != 0) {
303 // This entry was delivered, so add information on how long we've been waiting
304 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
305 }
306 dump.append("\n");
307 }
308 return dump;
309}
310
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700311/**
312 * Find the entry in std::unordered_map by key, and return it.
313 * If the entry is not found, return a default constructed entry.
314 *
315 * Useful when the entries are vectors, since an empty vector will be returned
316 * if the entry is not found.
317 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
318 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700319template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000320V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700321 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700322 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700326 if (first == second) {
327 return true;
328 }
329
330 if (first == nullptr || second == nullptr) {
331 return false;
332 }
333
334 return first->getToken() == second->getToken();
335}
336
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000338 if (first == nullptr || second == nullptr) {
339 return false;
340 }
341 return first->applicationInfo.token != nullptr &&
342 first->applicationInfo.token == second->applicationInfo.token;
343}
344
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800345template <typename T>
346size_t firstMarkedBit(T set) {
347 // TODO: replace with std::countr_zero from <bit> when that's available
348 LOG_ALWAYS_FATAL_IF(set.none());
349 size_t i = 0;
350 while (!set.test(i)) {
351 i++;
352 }
353 return i;
354}
355
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800356std::unique_ptr<DispatchEntry> createDispatchEntry(
357 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
358 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700359 if (inputTarget.useDefaultPointerTransform()) {
360 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700361 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700362 inputTarget.displayTransform,
363 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364 }
365
366 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
367 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
368
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700369 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700370 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371
372 // Use the first pointer information to normalize all other pointers. This could be any pointer
373 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700374 // uses the transform for the normalized pointer.
375 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800376 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700377 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700380 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000381 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
382 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700383 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000384
385 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700386 // First, apply the current pointer's transform to update the coordinates into
387 // window space.
388 pointerCoords[pointerIndex].transform(currTransform);
389 // Next, apply the inverse transform of the normalized coordinates so the
390 // current coordinates are transformed into the normalized coordinate space.
391 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000392 }
393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700394 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000395 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
396 motionEntry.eventTime, motionEntry.deviceId,
397 motionEntry.source, motionEntry.displayId,
398 motionEntry.policyFlags, motionEntry.action,
399 motionEntry.actionButton, motionEntry.flags,
400 motionEntry.metaState, motionEntry.buttonState,
401 motionEntry.classification, motionEntry.edgeFlags,
402 motionEntry.xPrecision, motionEntry.yPrecision,
403 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
404 motionEntry.downTime, motionEntry.pointerProperties,
405 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000406
407 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700408 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700409 firstPointerTransform, inputTarget.displayTransform,
410 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000411 return dispatchEntry;
412}
413
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000414status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
415 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700416 std::unique_ptr<InputChannel> uniqueServerChannel;
417 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
418
419 serverChannel = std::move(uniqueServerChannel);
420 return result;
421}
422
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500423template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000424bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500425 if (lhs == nullptr && rhs == nullptr) {
426 return true;
427 }
428 if (lhs == nullptr || rhs == nullptr) {
429 return false;
430 }
431 return *lhs == *rhs;
432}
433
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000434KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000435 KeyEvent event;
436 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
437 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
438 entry.repeatCount, entry.downTime, entry.eventTime);
439 return event;
440}
441
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000442bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000443 // Do not keep track of gesture monitors. They receive every event and would disproportionately
444 // affect the statistics.
445 if (connection.monitor) {
446 return false;
447 }
448 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
449 if (!connection.responsive) {
450 return false;
451 }
452 return true;
453}
454
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000455bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000456 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
457 const int32_t& inputEventId = eventEntry.id;
458 if (inputEventId != dispatchEntry.resolvedEventId) {
459 // Event was transmuted
460 return false;
461 }
462 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
463 return false;
464 }
465 // Only track latency for events that originated from hardware
466 if (eventEntry.isSynthesized()) {
467 return false;
468 }
469 const EventEntry::Type& inputEventEntryType = eventEntry.type;
470 if (inputEventEntryType == EventEntry::Type::KEY) {
471 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
472 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
473 return false;
474 }
475 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
476 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
477 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
478 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
479 return false;
480 }
481 } else {
482 // Not a key or a motion
483 return false;
484 }
485 if (!shouldReportMetricsForConnection(connection)) {
486 return false;
487 }
488 return true;
489}
490
Prabir Pradhancef936d2021-07-21 16:17:52 +0000491/**
492 * Connection is responsive if it has no events in the waitQueue that are older than the
493 * current time.
494 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000495bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000496 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000497 for (const auto& dispatchEntry : connection.waitQueue) {
498 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000499 return false;
500 }
501 }
502 return true;
503}
504
Antonio Kantekf16f2832021-09-28 04:39:20 +0000505// Returns true if the event type passed as argument represents a user activity.
506bool isUserActivityEvent(const EventEntry& eventEntry) {
507 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000508 case EventEntry::Type::CONFIGURATION_CHANGED:
509 case EventEntry::Type::DEVICE_RESET:
510 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000511 case EventEntry::Type::FOCUS:
512 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000514 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000516 case EventEntry::Type::KEY:
517 case EventEntry::Type::MOTION:
518 return true;
519 }
520}
521
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800522// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000523bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000524 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800525 const auto inputConfig = windowInfo.inputConfig;
526 if (windowInfo.displayId != displayId ||
527 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800528 return false;
529 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700530 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800531 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800532 return false;
533 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000534
535 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
536 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
537 // the window. Points on the right and bottom edges should not be inside the window, so we need
538 // to be careful about performing a hit test when the display is rotated, since the "right" and
539 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
540 // logical display in which WM determined the bounds. Perform the hit test in the logical
541 // display space to ensure these edges are considered correctly in all orientations.
542 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
543 const auto p = displayTransform.transform(x, y);
544 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800545 return false;
546 }
547 return true;
548}
549
Prabir Pradhand65552b2021-10-07 11:23:50 -0700550bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
551 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000552 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700553}
554
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800555// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000556// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
557// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
558// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800559// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000560bool canReceiveForegroundTouches(const WindowInfo& info) {
561 // A non-touchable window can still receive touch events (e.g. in the case of
562 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
563 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
564}
565
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000566bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700567 if (windowHandle == nullptr) {
568 return false;
569 }
570 const WindowInfo* windowInfo = windowHandle->getInfo();
571 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
572 return true;
573 }
574 return false;
575}
576
Prabir Pradhan5735a322022-04-11 17:23:34 +0000577// Checks targeted injection using the window's owner's uid.
578// Returns an empty string if an entry can be sent to the given window, or an error message if the
579// entry is a targeted injection whose uid target doesn't match the window owner.
580std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
581 const EventEntry& entry) {
582 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
583 // The event was not injected, or the injected event does not target a window.
584 return {};
585 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000586 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000587 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000588 return StringPrintf("No valid window target for injection into uid %s.",
589 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000590 }
591 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000592 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
593 "owned by uid %s.",
594 uid.toString().c_str(), window->getName().c_str(),
595 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000596 }
597 return {};
598}
599
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000600std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700601 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
602 // Always dispatch mouse events to cursor position.
603 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000604 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700605 }
606
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700607 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000608 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
609 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700610}
611
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700612std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
613 if (eventEntry.type == EventEntry::Type::KEY) {
614 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
615 return keyEntry.downTime;
616 } else if (eventEntry.type == EventEntry::Type::MOTION) {
617 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
618 return motionEntry.downTime;
619 }
620 return std::nullopt;
621}
622
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000623/**
624 * Compare the old touch state to the new touch state, and generate the corresponding touched
625 * windows (== input targets).
626 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
627 * If the pointer just entered the new window, produce HOVER_ENTER.
628 * For pointers remaining in the window, produce HOVER_MOVE.
629 */
630std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
631 const TouchState& newTouchState,
632 const MotionEntry& entry) {
633 std::vector<TouchedWindow> out;
634 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700635
636 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
637 // ACTION_SCROLL events should not affect the hovering pointer dispatch
638 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000639 }
640
641 // We should consider all hovering pointers here. But for now, just use the first one
642 const int32_t pointerId = entry.pointerProperties[0].id;
643
644 std::set<sp<WindowInfoHandle>> oldWindows;
645 if (oldState != nullptr) {
646 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
647 }
648
649 std::set<sp<WindowInfoHandle>> newWindows =
650 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
651
652 // If the pointer is no longer in the new window set, send HOVER_EXIT.
653 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
654 if (newWindows.find(oldWindow) == newWindows.end()) {
655 TouchedWindow touchedWindow;
656 touchedWindow.windowHandle = oldWindow;
657 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658 out.push_back(touchedWindow);
659 }
660 }
661
662 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = newWindow;
665 if (oldWindows.find(newWindow) == oldWindows.end()) {
666 // Any windows that have this pointer now, and didn't have it before, should get
667 // HOVER_ENTER
668 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
669 } else {
670 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700671 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700672 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000673 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
674 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700675 // The Accessibility injected touch exploration event stream
676 // has known inconsistencies, so log ERROR instead of
677 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700678 severity = android::base::LogSeverity::ERROR;
679 }
680 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700681 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000682 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
683 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700684 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
686 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
687 }
688 out.push_back(touchedWindow);
689 }
690 return out;
691}
692
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800693template <typename T>
694std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
695 left.insert(left.end(), right.begin(), right.end());
696 return left;
697}
698
Harry Cuttsb166c002023-05-09 13:06:05 +0000699// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
700// both.
701void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
702 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
703 if (!window.windowHandle->getInfo()->inputConfig.test(
704 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
705 // In addition to TouchState, erase this window from the input targets! We don't have a
706 // good way to do this today except by adding a nested loop.
707 // TODO(b/282025641): simplify this code once InputTargets are being identified
708 // separately from TouchedWindows.
709 std::erase_if(targets, [&](const InputTarget& target) {
710 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
711 });
712 return true;
713 }
714 return false;
715 });
716}
717
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700718/**
719 * In general, touch should be always split between windows. Some exceptions:
720 * 1. Don't split touch if all of the below is true:
721 * (a) we have an active pointer down *and*
722 * (b) a new pointer is going down that's from the same device *and*
723 * (c) the window that's receiving the current pointer does not support split touch.
724 * 2. Don't split mouse events
725 */
726bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
727 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
728 // We should never split mouse events
729 return false;
730 }
731 for (const TouchedWindow& touchedWindow : touchState.windows) {
732 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
733 // Spy windows should not affect whether or not touch is split.
734 continue;
735 }
736 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
737 continue;
738 }
739 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
740 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
741 // Wallpaper window should not affect whether or not touch is split
742 continue;
743 }
744
745 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
746 return false;
747 }
748 }
749 return true;
750}
751
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000752} // namespace
753
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754// --- InputDispatcher ---
755
Prabir Pradhana41d2442023-04-20 21:30:40 +0000756InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Garfield Tan00f511d2019-06-12 16:55:40 -0700757 : mPolicy(policy),
758 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700759 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800760 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700761 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700762 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700763 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800764 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700765 mDispatchEnabled(false),
766 mDispatchFrozen(false),
767 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100768 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000769 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800770 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000771 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000772 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700773 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800774 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700776 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700777#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700778 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700779#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700780 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781}
782
783InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000784 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785
Prabir Pradhancef936d2021-07-21 16:17:52 +0000786 resetKeyRepeatLocked();
787 releasePendingEventLocked();
788 drainInboundQueueLocked();
789 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000791 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700792 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000793 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 }
795}
796
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700797status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700798 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700799 return ALREADY_EXISTS;
800 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700801 mThread = std::make_unique<InputThread>(
802 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
803 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804}
805
806status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700807 if (mThread && mThread->isCallingThread()) {
808 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700809 return INVALID_OPERATION;
810 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700811 mThread.reset();
812 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700813}
814
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700816 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800818 std::scoped_lock _l(mLock);
819 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820
821 // Run a dispatch loop if there are no pending commands.
822 // The dispatch loop might enqueue commands to run afterwards.
823 if (!haveCommandsLocked()) {
824 dispatchOnceInnerLocked(&nextWakeupTime);
825 }
826
827 // Run all pending commands if there are any.
828 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000829 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700830 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800832
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700833 // If we are still waiting for ack on some events,
834 // we might have to wake up earlier to check if an app is anr'ing.
835 const nsecs_t nextAnrCheck = processAnrsLocked();
836 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
837
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800838 // We are about to enter an infinitely long sleep, because we have no commands or
839 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700840 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800841 mDispatcherEnteredIdle.notify_all();
842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 } // release lock
844
845 // Wait for callback or timeout or wake. (make sure we round up, not down)
846 nsecs_t currentTime = now();
847 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
848 mLooper->pollOnce(timeoutMillis);
849}
850
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700851/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500852 * Raise ANR if there is no focused window.
853 * Before the ANR is raised, do a final state check:
854 * 1. The currently focused application must be the same one we are waiting for.
855 * 2. Ensure we still don't have a focused window.
856 */
857void InputDispatcher::processNoFocusedWindowAnrLocked() {
858 // Check if the application that we are waiting for is still focused.
859 std::shared_ptr<InputApplicationHandle> focusedApplication =
860 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
861 if (focusedApplication == nullptr ||
862 focusedApplication->getApplicationToken() !=
863 mAwaitedFocusedApplication->getApplicationToken()) {
864 // Unexpected because we should have reset the ANR timer when focused application changed
865 ALOGE("Waited for a focused window, but focused application has already changed to %s",
866 focusedApplication->getName().c_str());
867 return; // The focused application has changed.
868 }
869
chaviw98318de2021-05-19 16:45:23 -0500870 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500871 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
872 if (focusedWindowHandle != nullptr) {
873 return; // We now have a focused window. No need for ANR.
874 }
875 onAnrLocked(mAwaitedFocusedApplication);
876}
877
878/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700879 * Check if any of the connections' wait queues have events that are too old.
880 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
881 * Return the time at which we should wake up next.
882 */
883nsecs_t InputDispatcher::processAnrsLocked() {
884 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700885 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
887 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
888 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500889 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700890 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500891 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700892 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500894 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
896 }
897 }
898
899 // Check if any connection ANRs are due
900 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
901 if (currentTime < nextAnrCheck) { // most likely scenario
902 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
903 }
904
905 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700906 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700907 if (connection == nullptr) {
908 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
909 return nextAnrCheck;
910 }
911 connection->responsive = false;
912 // Stop waking up for this unresponsive connection
913 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000914 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700915 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700916}
917
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800918std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700919 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800920 if (connection->monitor) {
921 return mMonitorDispatchingTimeout;
922 }
923 const sp<WindowInfoHandle> window =
924 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500926 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500928 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929}
930
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
932 nsecs_t currentTime = now();
933
Jeff Browndc5992e2014-04-11 01:27:26 -0700934 // Reset the key repeat timer whenever normal dispatch is suspended while the
935 // device is in a non-interactive state. This is to ensure that we abort a key
936 // repeat if the device is just coming out of sleep.
937 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 resetKeyRepeatLocked();
939 }
940
941 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
942 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100943 if (DEBUG_FOCUS) {
944 ALOGD("Dispatch frozen. Waiting some more.");
945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 return;
947 }
948
949 // Optimize latency of app switches.
950 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
951 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700952 bool isAppSwitchDue;
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700953 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700954 isAppSwitchDue = mAppSwitchDueTime <= currentTime;
955 if (mAppSwitchDueTime < *nextWakeupTime) {
956 *nextWakeupTime = mAppSwitchDueTime;
957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 }
959
960 // Ready to start a new event.
961 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700963 if (mInboundQueue.empty()) {
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700964 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700965 if (isAppSwitchDue) {
966 // The inbound queue is empty so the app switch key we were waiting
967 // for will never arrive. Stop waiting for it.
968 resetPendingAppSwitchLocked(false);
969 isAppSwitchDue = false;
970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
972
973 // Synthesize a key repeat if appropriate.
974 if (mKeyRepeatState.lastKeyEntry) {
975 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
976 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
977 } else {
978 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
979 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
980 }
981 }
982 }
983
984 // Nothing to do if there is no pending event.
985 if (!mPendingEvent) {
986 return;
987 }
988 } else {
989 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mPendingEvent = mInboundQueue.front();
991 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 traceInboundQueueLengthLocked();
993 }
994
995 // Poke user activity for this event.
996 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000
1001 // Now we have an event to dispatch.
1002 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001003 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
1012 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001013 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 const ConfigurationChangedEntry& typedEntry =
1019 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 break;
1023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001025 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 const DeviceResetEntry& typedEntry =
1027 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
1031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 std::shared_ptr<FocusEntry> typedEntry =
1035 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001036 dispatchFocusLocked(currentTime, typedEntry);
1037 done = true;
1038 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1039 break;
1040 }
1041
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001042 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1043 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1044 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1045 done = true;
1046 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1047 break;
1048 }
1049
Prabir Pradhan99987712020-11-10 18:43:05 -08001050 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1051 const auto typedEntry =
1052 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1053 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1054 done = true;
1055 break;
1056 }
1057
arthurhungb89ccb02020-12-30 16:19:01 +08001058 case EventEntry::Type::DRAG: {
1059 std::shared_ptr<DragEntry> typedEntry =
1060 std::static_pointer_cast<DragEntry>(mPendingEvent);
1061 dispatchDragLocked(currentTime, typedEntry);
1062 done = true;
1063 break;
1064 }
1065
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001068 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001069 if (isAppSwitchDue) {
1070 if (isAppSwitchKeyEvent(*keyEntry)) {
1071 resetPendingAppSwitchLocked(true);
1072 isAppSwitchDue = false;
1073 } else if (dropReason == DropReason::NOT_DROPPED) {
1074 dropReason = DropReason::APP_SWITCH;
1075 }
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 Vishniakou17f12282023-11-02 13:40:29 -07001091 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001092 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1093 dropReason = DropReason::APP_SWITCH;
1094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001096 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1100 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001102 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
Chris Yef59a2f42020-10-16 12:55:26 -07001105
1106 case EventEntry::Type::SENSOR: {
1107 std::shared_ptr<SensorEntry> sensorEntry =
1108 std::static_pointer_cast<SensorEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001109 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001110 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1111 dropReason = DropReason::APP_SWITCH;
1112 }
Chris Yef59a2f42020-10-16 12:55:26 -07001113 }
1114 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1115 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1116 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1117 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1118 dropReason = DropReason::STALE;
1119 }
1120 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1121 done = true;
1122 break;
1123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 }
1125
1126 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001127 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001128 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 }
Michael Wright3a981722015-06-10 15:26:13 +01001130 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131
1132 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001133 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 }
1135}
1136
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001137bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001138 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001139}
1140
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001141/**
1142 * Return true if the events preceding this incoming motion event should be dropped
1143 * Return false otherwise (the default behaviour)
1144 */
1145bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001146 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001147 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001148
1149 // Optimize case where the current application is unresponsive and the user
1150 // decides to touch a window in a different application.
1151 // If the application takes too long to catch up then we drop all events preceding
1152 // the touch into the other window.
1153 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001154 const int32_t displayId = motionEntry.displayId;
1155 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001156 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001157
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001158 sp<WindowInfoHandle> touchedWindowHandle =
1159 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001160 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001161 touchedWindowHandle->getApplicationToken() !=
1162 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001163 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001164 ALOGI("Pruning input queue because user touched a different application while waiting "
1165 "for %s",
1166 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001167 return true;
1168 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001169
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001170 // Alternatively, maybe there's a spy window that could handle this event.
1171 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1172 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1173 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001174 const std::shared_ptr<Connection> connection =
1175 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001176 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001177 // This spy window could take more input. Drop all events preceding this
1178 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001179 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001180 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001181 mAwaitedFocusedApplication->getName().c_str());
1182 return true;
1183 }
1184 }
1185 }
1186
1187 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1188 // yet been processed by some connections, the dispatcher will wait for these motion
1189 // events to be processed before dispatching the key event. This is because these motion events
1190 // may cause a new window to be launched, which the user might expect to receive focus.
1191 // To prevent waiting forever for such events, just send the key to the currently focused window
1192 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1193 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1194 "just send the pending key event to the focused window.");
1195 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001196 }
1197 return false;
1198}
1199
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001201 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 mInboundQueue.push_back(std::move(newEntry));
1203 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 traceInboundQueueLengthLocked();
1205
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001206 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001207 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001208 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1209 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 // Optimize app switch latency.
1211 // If the application takes too long to catch up then we drop all events preceding
1212 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001213 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001214
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001215 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001216 if (isAppSwitchKeyEvent(keyEntry)) {
1217 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
1218 mAppSwitchSawKeyDown = true;
1219 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
1220 if (mAppSwitchSawKeyDown) {
1221 if (DEBUG_APP_SWITCH) {
1222 ALOGD("App switch is pending!");
1223 }
1224 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
1225 mAppSwitchSawKeyDown = false;
1226 needWake = true;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001227 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 }
1229 }
1230 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001231 // If a new up event comes in, and the pending event with same key code has been asked
1232 // to try again later because of the policy. We have to reset the intercept key wake up
1233 // time for it may have been handled in the policy and could be dropped.
1234 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1235 mPendingEvent->type == EventEntry::Type::KEY) {
1236 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1237 if (pendingKey.keyCode == keyEntry.keyCode &&
1238 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001239 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1240 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001241 pendingKey.interceptKeyWakeupTime = 0;
1242 needWake = true;
1243 }
1244 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 break;
1246 }
1247
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001248 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001249 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1250 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1252 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001253 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001257 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001258 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1259 break;
1260 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001261 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001262 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001263 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001264 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001265 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1266 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001267 // nothing to do
1268 break;
1269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 }
1271
1272 return needWake;
1273}
1274
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001276 // Do not store sensor event in recent queue to avoid flooding the queue.
1277 if (entry->type != EventEntry::Type::SENSOR) {
1278 mRecentQueue.push_back(entry);
1279 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001280 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001281 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 }
1283}
1284
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001285sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1286 bool isStylus,
1287 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001289 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001290 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001291 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001292 continue;
1293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001295 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001296 if (!info.isSpy() &&
1297 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001298 return windowHandle;
1299 }
1300 }
1301 return nullptr;
1302}
1303
1304std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001305 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001306 if (touchedWindow == nullptr) {
1307 return {};
1308 }
1309 // Traverse windows from front to back until we encounter the touched window.
1310 std::vector<InputTarget> outsideTargets;
1311 const auto& windowHandles = getWindowHandlesLocked(displayId);
1312 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1313 if (windowHandle == touchedWindow) {
1314 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1315 // below the touched window will not get ACTION_OUTSIDE event.
1316 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001317 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001318
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001319 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001320 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001321 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1322 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001323 addPointerWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1324 pointerIds,
1325 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
1327 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001328 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329}
1330
Prabir Pradhand65552b2021-10-07 11:23:50 -07001331std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001332 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001333 // Traverse windows from front to back and gather the touched spy windows.
1334 std::vector<sp<WindowInfoHandle>> spyWindows;
1335 const auto& windowHandles = getWindowHandlesLocked(displayId);
1336 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1337 const WindowInfo& info = *windowHandle->getInfo();
1338
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001339 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001340 continue;
1341 }
1342 if (!info.isSpy()) {
1343 // The first touched non-spy window was found, so return the spy windows touched so far.
1344 return spyWindows;
1345 }
1346 spyWindows.push_back(windowHandle);
1347 }
1348 return spyWindows;
1349}
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 const char* reason;
1353 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001354 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001355 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001356 ALOGD("Dropped event because policy consumed it.");
1357 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 reason = "inbound event was dropped because the policy consumed it";
1359 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001360 case DropReason::DISABLED:
1361 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 ALOGI("Dropped event because input dispatch is disabled.");
1363 }
1364 reason = "inbound event was dropped because input dispatch is disabled";
1365 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001366 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001367 ALOGI("Dropped event because of pending overdue app switch.");
1368 reason = "inbound event was dropped because of pending overdue app switch";
1369 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001370 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371 ALOGI("Dropped event because the current application is not responding and the user "
1372 "has started interacting with a different application.");
1373 reason = "inbound event was dropped because the current application is not responding "
1374 "and the user has started interacting with a different application";
1375 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001376 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001377 ALOGI("Dropped event because it is stale.");
1378 reason = "inbound event was dropped because it is stale";
1379 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001380 case DropReason::NO_POINTER_CAPTURE:
1381 ALOGI("Dropped event because there is no window with Pointer Capture.");
1382 reason = "inbound event was dropped because there is no window with Pointer Capture";
1383 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001384 case DropReason::NOT_DROPPED: {
1385 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001386 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
1389
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001390 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001391 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001392 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001396 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001397 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1398 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001399 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001400 synthesizeCancelationEventsForAllConnectionsLocked(options);
1401 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001402 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1403 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 synthesizeCancelationEventsForAllConnectionsLocked(options);
1405 }
1406 break;
1407 }
Chris Yef59a2f42020-10-16 12:55:26 -07001408 case EventEntry::Type::SENSOR: {
1409 break;
1410 }
arthurhungb89ccb02020-12-30 16:19:01 +08001411 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1412 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001413 break;
1414 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001415 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001416 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001417 case EventEntry::Type::CONFIGURATION_CHANGED:
1418 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001419 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001420 break;
1421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 }
1423}
1424
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001425static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001426 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1427 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428}
1429
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001430bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1431 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1432 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1433 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434}
1435
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001436bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001437 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438}
1439
1440void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001441 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001443 if (DEBUG_APP_SWITCH) {
1444 if (handled) {
1445 ALOGD("App switch has arrived.");
1446 } else {
1447 ALOGD("App switch was abandoned.");
1448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450}
1451
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001453 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454}
1455
Prabir Pradhancef936d2021-07-21 16:17:52 +00001456bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 return false;
1459 }
1460
1461 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001462 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001463 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001464 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1465 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001466 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 return true;
1468}
1469
Prabir Pradhancef936d2021-07-21 16:17:52 +00001470void InputDispatcher::postCommandLocked(Command&& command) {
1471 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472}
1473
1474void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001475 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001476 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001477 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 releaseInboundEventLocked(entry);
1479 }
1480 traceInboundQueueLengthLocked();
1481}
1482
1483void InputDispatcher::releasePendingEventLocked() {
1484 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001486 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488}
1489
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001490void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001491 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001492 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001493 if (DEBUG_DISPATCH_CYCLE) {
1494 ALOGD("Injected inbound event was dropped.");
1495 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001496 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 }
1498 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001499 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 }
1501 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502}
1503
1504void InputDispatcher::resetKeyRepeatLocked() {
1505 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001506 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 }
1508}
1509
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1511 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512
Michael Wright2e732952014-09-24 13:26:59 -07001513 uint32_t policyFlags = entry->policyFlags &
1514 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001517 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1518 currentTime, entry->deviceId, entry->source,
1519 entry->displayId, policyFlags, entry->action, entry->flags,
1520 entry->keyCode, entry->scanCode, entry->metaState,
1521 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523 newEntry->syntheticRepeat = true;
1524 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001526 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527}
1528
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001529bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001530 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001531 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1532 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534
1535 // Reset key repeating in case a keyboard device was added or removed or something.
1536 resetKeyRepeatLocked();
1537
1538 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001539 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1540 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001541 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001542 };
1543 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 return true;
1545}
1546
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001547bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1548 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001549 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1550 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1551 entry.deviceId);
1552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553
liushenxiang42232912021-05-21 20:24:09 +08001554 // Reset key repeating in case a keyboard device was disabled or enabled.
1555 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1556 resetKeyRepeatLocked();
1557 }
1558
Michael Wrightfb04fd52022-11-24 22:31:11 +00001559 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001562
1563 // Remove all active pointers from this device
1564 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1565 touchState.removeAllPointersForDevice(entry.deviceId);
1566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return true;
1568}
1569
Vishnu Nairad321cd2020-08-20 16:40:21 -07001570void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001571 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001572 if (mPendingEvent != nullptr) {
1573 // Move the pending event to the front of the queue. This will give the chance
1574 // for the pending event to get dispatched to the newly focused window
1575 mInboundQueue.push_front(mPendingEvent);
1576 mPendingEvent = nullptr;
1577 }
1578
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001579 std::unique_ptr<FocusEntry> focusEntry =
1580 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1581 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001582
1583 // This event should go to the front of the queue, but behind all other focus events
1584 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001586 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587 [](const std::shared_ptr<EventEntry>& event) {
1588 return event->type == EventEntry::Type::FOCUS;
1589 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001590
1591 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001592 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001593}
1594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001596 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001597 if (channel == nullptr) {
1598 return; // Window has gone away
1599 }
1600 InputTarget target;
1601 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001602 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001603 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001604 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1605 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001606 std::string reason = std::string("reason=").append(entry->reason);
1607 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001608 dispatchEventLocked(currentTime, entry, {target});
1609}
1610
Prabir Pradhan99987712020-11-10 18:43:05 -08001611void InputDispatcher::dispatchPointerCaptureChangedLocked(
1612 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1613 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001614 dropReason = DropReason::NOT_DROPPED;
1615
Prabir Pradhan99987712020-11-10 18:43:05 -08001616 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001617 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001618
1619 if (entry->pointerCaptureRequest.enable) {
1620 // Enable Pointer Capture.
1621 if (haveWindowWithPointerCapture &&
1622 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001623 // This can happen if pointer capture is disabled and re-enabled before we notify the
1624 // app of the state change, so there is no need to notify the app.
1625 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1626 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001627 }
1628 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001629 // This can happen if a window requests capture and immediately releases capture.
1630 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001631 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001632 return;
1633 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001634 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1635 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1636 return;
1637 }
1638
Vishnu Nairc519ff72021-01-21 08:23:08 -08001639 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001640 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1641 mWindowTokenWithPointerCapture = token;
1642 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001643 // Disable Pointer Capture.
1644 // We do not check if the sequence number matches for requests to disable Pointer Capture
1645 // for two reasons:
1646 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1647 // to disable capture with the same sequence number: one generated by
1648 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1649 // Capture being disabled in InputReader.
1650 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1651 // actual Pointer Capture state that affects events being generated by input devices is
1652 // in InputReader.
1653 if (!haveWindowWithPointerCapture) {
1654 // Pointer capture was already forcefully disabled because of focus change.
1655 dropReason = DropReason::NOT_DROPPED;
1656 return;
1657 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001658 token = mWindowTokenWithPointerCapture;
1659 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001660 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001661 setPointerCaptureLocked(false);
1662 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001663 }
1664
1665 auto channel = getInputChannelLocked(token);
1666 if (channel == nullptr) {
1667 // Window has gone away, clean up Pointer Capture state.
1668 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001669 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001670 setPointerCaptureLocked(false);
1671 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001672 return;
1673 }
1674 InputTarget target;
1675 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001676 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001677 entry->dispatchInProgress = true;
1678 dispatchEventLocked(currentTime, entry, {target});
1679
1680 dropReason = DropReason::NOT_DROPPED;
1681}
1682
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001683void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1684 const std::shared_ptr<TouchModeEntry>& entry) {
1685 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001686 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001687 if (windowHandles.empty()) {
1688 return;
1689 }
1690 const std::vector<InputTarget> inputTargets =
1691 getInputTargetsFromWindowHandlesLocked(windowHandles);
1692 if (inputTargets.empty()) {
1693 return;
1694 }
1695 entry->dispatchInProgress = true;
1696 dispatchEventLocked(currentTime, entry, inputTargets);
1697}
1698
1699std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1700 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1701 std::vector<InputTarget> inputTargets;
1702 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001703 const sp<IBinder>& token = handle->getToken();
1704 if (token == nullptr) {
1705 continue;
1706 }
1707 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1708 if (channel == nullptr) {
1709 continue; // Window has gone away
1710 }
1711 InputTarget target;
1712 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001713 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001714 inputTargets.push_back(target);
1715 }
1716 return inputTargets;
1717}
1718
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001719bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001720 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001722 if (!entry->dispatchInProgress) {
1723 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1724 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1725 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1726 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001727 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 // We have seen two identical key downs in a row which indicates that the device
1729 // driver is automatically generating key repeats itself. We take note of the
1730 // repeat here, but we disable our own next key repeat timer since it is clear that
1731 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001732 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1733 // Make sure we don't get key down from a different device. If a different
1734 // device Id has same key pressed down, the new device Id will replace the
1735 // current one to hold the key repeat with repeat count reset.
1736 // In the future when got a KEY_UP on the device id, drop it and do not
1737 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1739 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001740 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 } else {
1742 // Not a repeat. Save key down state in case we do see a repeat later.
1743 resetKeyRepeatLocked();
1744 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1745 }
1746 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001747 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1748 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001749 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001750 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001751 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1752 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001753 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 resetKeyRepeatLocked();
1755 }
1756
1757 if (entry->repeatCount == 1) {
1758 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1759 } else {
1760 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1761 }
1762
1763 entry->dispatchInProgress = true;
1764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001765 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 }
1767
1768 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001769 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 if (currentTime < entry->interceptKeyWakeupTime) {
1771 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1772 *nextWakeupTime = entry->interceptKeyWakeupTime;
1773 }
1774 return false; // wait until next wakeup
1775 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001776 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 entry->interceptKeyWakeupTime = 0;
1778 }
1779
1780 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001781 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001783 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001784 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001785
1786 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1787 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1788 };
1789 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001790 // Poke user activity for keys not passed to user
1791 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 return false; // wait for the command to run
1793 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001794 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001796 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001797 if (*dropReason == DropReason::NOT_DROPPED) {
1798 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800 }
1801
1802 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001803 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001804 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001805 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1806 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001807 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001808 // Poke user activity for undispatched keys
1809 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 return true;
1811 }
1812
1813 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001814 InputEventInjectionResult injectionResult;
1815 sp<WindowInfoHandle> focusedWindow =
1816 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1817 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001818 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 return false;
1820 }
1821
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001822 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001823 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 return true;
1825 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001826 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1827
1828 std::vector<InputTarget> inputTargets;
1829 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001830 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001831 getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001833 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835
1836 // Dispatch the key.
1837 dispatchEventLocked(currentTime, entry, inputTargets);
1838 return true;
1839}
1840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001842 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1843 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1844 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1845 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1846 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1847 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1848 entry.metaState, entry.repeatCount, entry.downTime);
1849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850}
1851
Prabir Pradhancef936d2021-07-21 16:17:52 +00001852void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1853 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001854 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001855 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1856 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1857 "source=0x%x, sensorType=%s",
1858 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001859 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001860 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001861 auto command = [this, entry]() REQUIRES(mLock) {
1862 scoped_unlock unlock(mLock);
1863
1864 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001865 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001866 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001867 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1868 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001869 };
1870 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001871}
1872
1873bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001874 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1875 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001876 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001877 }
Chris Yef59a2f42020-10-16 12:55:26 -07001878 { // acquire lock
1879 std::scoped_lock _l(mLock);
1880
1881 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1882 std::shared_ptr<EventEntry> entry = *it;
1883 if (entry->type == EventEntry::Type::SENSOR) {
1884 it = mInboundQueue.erase(it);
1885 releaseInboundEventLocked(entry);
1886 }
1887 }
1888 }
1889 return true;
1890}
1891
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001892bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001894 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001896 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 entry->dispatchInProgress = true;
1898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001899 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901
1902 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001903 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001904 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001905 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1906 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 return true;
1908 }
1909
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001910 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911
1912 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001913 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001915 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 if (isPointerEvent) {
1917 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001918
1919 if (mDragState &&
1920 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1921 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1922 pilferPointersLocked(mDragState->dragWindow->getToken());
1923 }
1924
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001925 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001926 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001927 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1928 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 } else {
1930 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001931 sp<WindowInfoHandle> focusedWindow =
1932 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1933 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1934 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1935 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001936 InputTarget::Flags::FOREGROUND |
1937 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001938 getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001941 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 return false;
1943 }
1944
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001945 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001946 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001947 return true;
1948 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001949 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001950 CancelationOptions::Mode mode(
1951 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1952 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001953 CancelationOptions options(mode, "input event injection failed");
1954 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 return true;
1956 }
1957
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001958 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001959 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960
1961 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 dispatchEventLocked(currentTime, entry, inputTargets);
1963 return true;
1964}
1965
chaviw98318de2021-05-19 16:45:23 -05001966void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001967 bool isExiting, const int32_t rawX,
1968 const int32_t rawY) {
1969 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001970 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001971 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1972 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001973
1974 enqueueInboundEventLocked(std::move(dragEntry));
1975}
1976
1977void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1978 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1979 if (channel == nullptr) {
1980 return; // Window has gone away
1981 }
1982 InputTarget target;
1983 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001984 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001985 entry->dispatchInProgress = true;
1986 dispatchEventLocked(currentTime, entry, {target});
1987}
1988
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001990 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001991 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001992 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001993 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001994 "metaState=0x%x, buttonState=0x%x,"
1995 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001996 prefix, entry.eventTime, entry.deviceId,
1997 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1998 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1999 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2000 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002002 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002003 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002004 "x=%f, y=%f, pressure=%f, size=%f, "
2005 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2006 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002007 i, entry.pointerProperties[i].id,
2008 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2015 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2016 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2017 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020}
2021
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002022void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2023 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002024 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002025 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002026 if (DEBUG_DISPATCH_CYCLE) {
2027 ALOGD("dispatchEventToCurrentInputTargets");
2028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002030 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002031
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2033
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002036 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002037 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002038 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002039 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002040 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002042 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2043 LOG(INFO) << "Dropping event delivery to target with channel "
2044 << inputTarget.inputChannel->getName()
2045 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048 }
2049}
2050
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002051void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2053 // If the policy decides to close the app, we will get a channel removal event via
2054 // unregisterInputChannel, and will clean up the connection that way. We are already not
2055 // sending new pointers to the connection when it blocked, but focused events will continue to
2056 // pile up.
2057 ALOGW("Canceling events for %s because it is unresponsive",
2058 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002059 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002060 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002061 "application not responding");
2062 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
2064}
2065
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002066void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002067 if (DEBUG_FOCUS) {
2068 ALOGD("Resetting ANR timeouts.");
2069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070
2071 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002073 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074}
2075
Tiger Huang721e26f2018-07-24 22:26:19 +08002076/**
2077 * Get the display id that the given event should go to. If this event specifies a valid display id,
2078 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2079 * Focused display is the display that the user most recently interacted with.
2080 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002081int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002082 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002083 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002084 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2086 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 break;
2088 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002089 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002090 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2091 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 break;
2093 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002094 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002095 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002096 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002097 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002098 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002099 case EventEntry::Type::SENSOR:
2100 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002101 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102 return ADISPLAY_ID_NONE;
2103 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002104 }
2105 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2106}
2107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002108bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2109 const char* focusedWindowName) {
2110 if (mAnrTracker.empty()) {
2111 // already processed all events that we waited for
2112 mKeyIsWaitingForEventsTimeout = std::nullopt;
2113 return false;
2114 }
2115
2116 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2117 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002118 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002119 mKeyIsWaitingForEventsTimeout = currentTime +
2120 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2121 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002122 return true;
2123 }
2124
2125 // We still have pending events, and already started the timer
2126 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2127 return true; // Still waiting
2128 }
2129
2130 // Waited too long, and some connection still hasn't processed all motions
2131 // Just send the key to the focused window
2132 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2133 focusedWindowName);
2134 mKeyIsWaitingForEventsTimeout = std::nullopt;
2135 return false;
2136}
2137
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002138sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2139 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2140 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002141 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002142 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
Tiger Huang721e26f2018-07-24 22:26:19 +08002144 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002145 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002146 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002147 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2148
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 // If there is no currently focused window and no focused application
2150 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2152 ALOGI("Dropping %s event because there is no focused window or focused application in "
2153 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002154 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002155 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157
Vishnu Nair062a8672021-09-03 16:07:44 -07002158 // Drop key events if requested by input feature
2159 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002160 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002161 }
2162
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2164 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2165 // start interacting with another application via touch (app switch). This code can be removed
2166 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2167 // an app is expected to have a focused window.
2168 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2169 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2170 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002171 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2172 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2173 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002175 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 ALOGW("Waiting because no window has focus but %s may eventually add a "
2177 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002178 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002180 outInjectionResult = InputEventInjectionResult::PENDING;
2181 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2183 // Already raised ANR. Drop the event
2184 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002185 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002187 } else {
2188 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002189 outInjectionResult = InputEventInjectionResult::PENDING;
2190 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002191 }
2192 }
2193
2194 // we have a valid, non-null focused window
2195 resetNoFocusedWindowTimeoutLocked();
2196
Prabir Pradhan5735a322022-04-11 17:23:34 +00002197 // Verify targeted injection.
2198 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2199 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002200 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2201 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
2203
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002204 if (focusedWindowHandle->getInfo()->inputConfig.test(
2205 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002207 outInjectionResult = InputEventInjectionResult::PENDING;
2208 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002209 }
2210
2211 // If the event is a key event, then we must wait for all previous events to
2212 // complete before delivering it because previous events may have the
2213 // side-effect of transferring focus to a different window and we want to
2214 // ensure that the following keys are sent to the new window.
2215 //
2216 // Suppose the user touches a button in a window then immediately presses "A".
2217 // If the button causes a pop-up window to appear then we want to ensure that
2218 // the "A" key is delivered to the new pop-up window. This is because users
2219 // often anticipate pending UI changes when typing on a keyboard.
2220 // To obtain this behavior, we must serialize key events with respect to all
2221 // prior input events.
2222 if (entry.type == EventEntry::Type::KEY) {
2223 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2224 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002225 outInjectionResult = InputEventInjectionResult::PENDING;
2226 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
2229
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002230 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2231 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232}
2233
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234/**
2235 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2236 * that are currently unresponsive.
2237 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002238std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2239 const std::vector<Monitor>& monitors) const {
2240 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002242 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002243 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002244 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 if (connection == nullptr) {
2246 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002247 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002248 return false;
2249 }
2250 if (!connection->responsive) {
2251 ALOGW("Unresponsive monitor %s will not get the new gesture",
2252 connection->inputChannel->getName().c_str());
2253 return false;
2254 }
2255 return true;
2256 });
2257 return responsiveMonitors;
2258}
2259
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002260std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002261 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002262 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002263 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002265 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 // For security reasons, we defer updating the touch state until we are sure that
2267 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 const int32_t displayId = entry.displayId;
2269 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002270 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
2272 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002273 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002275 // Copy current touch state into tempTouchState.
2276 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2277 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002278 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002279 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2281 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002282 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002283 }
2284
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002285 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002286
2287 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2288 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2289 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002290 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2291 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002292 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002293 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2294 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002295 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2296 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2297 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002298 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002299
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002300 if (newGesture) {
2301 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002302 }
2303
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002304 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2305 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2306 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002309 if (isHoverAction) {
2310 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2311 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002312 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002313 }
2314
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2316 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002317 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002318 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002319 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002320 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2321 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002322 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002323 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002324 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002325
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002326 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002327 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002330 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002331 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002333 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002334 }
2335
Prabir Pradhan5735a322022-04-11 17:23:34 +00002336 // Verify targeted injection.
2337 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2338 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002339 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002340 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002341 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002342 }
2343
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002344 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002345 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002346 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2347 // New window supports splitting, but we should never split mouse events.
2348 isSplit = !isFromMouse;
2349 } else if (isSplit) {
2350 // New window does not support splitting but we have already split events.
2351 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002352 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2353 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002354 newTouchedWindowHandle = nullptr;
2355 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002356 } else {
2357 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002358 // be delivered to a new window which supports split touch. Pointers from a mouse device
2359 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002360 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002361 }
2362
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002363 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002364 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002366 // Process the foreground window first so that it is the first to receive the event.
2367 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 }
2369
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002370 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002371 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2372 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002373 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002374 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002375 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002376 }
2377
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002379 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380 continue;
2381 }
2382
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002383 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002384 // The "windowHandle" is the target of this hovering pointer.
2385 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002386 }
2387
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002389 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002390
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002391 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2392 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002393 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002394 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002395
2396 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002397 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398 }
2399 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002400 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002402 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002403 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002404
2405 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002406
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002407 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002408 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002409 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002410 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2411 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2412 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId,
2413 pointerIds,
2414 isDownOrPointerDown
2415 ? std::make_optional(entry.eventTime)
2416 : std::nullopt);
2417 // If this is the pointer going down and the touched window has a wallpaper
2418 // then also add the touched wallpaper windows so they are locked in for the
2419 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2420 // SCROLL because the wallpaper engine only supports touch events. We would need to
2421 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2422 // handle these events.
2423 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002424 windowHandle->getInfo()->inputConfig.test(
2425 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2426 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2427 if (wallpaper != nullptr) {
2428 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2429 InputTarget::Flags::WINDOW_IS_OBSCURED |
2430 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2431 InputTarget::Flags::DISPATCH_AS_IS;
2432 if (isSplit) {
2433 wallpaperFlags |= InputTarget::Flags::SPLIT;
2434 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002435 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2436 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002437 }
2438 }
2439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002441
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002442 // If a window is already pilfering some pointers, give it this new pointer as well and
2443 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2444 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002445 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002446 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2447 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002448 // This window is already pilfering some pointers, and this new pointer is also
2449 // going to it. Therefore, take over this pointer and don't give it to anyone
2450 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002451 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002452 }
2453 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002454
2455 // Restrict all pilfered pointers to the pilfering windows.
2456 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 } else {
2458 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2459
2460 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002461 if (!tempTouchState.isDown(entry.deviceId) &&
2462 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002463 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2464 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2465 << " is not down or we previously dropped the pointer down event in "
2466 << "display " << displayId << ": " << entry.getDescription();
2467 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002468 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002469 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
2471
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002472 // If the pointer is not currently hovering, then ignore the event.
2473 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2474 const int32_t pointerId = entry.pointerProperties[0].id;
2475 if (oldState == nullptr ||
2476 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2477 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2478 "display "
2479 << displayId << ": " << entry.getDescription();
2480 outInjectionResult = InputEventInjectionResult::FAILED;
2481 return {};
2482 }
2483 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2484 }
2485
arthurhung6d4bed92021-03-17 11:59:33 +08002486 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002487
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002489 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002490 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002491 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002492 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002493 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002494 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002495 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002496 sp<WindowInfoHandle> newTouchedWindowHandle =
2497 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002498
Prabir Pradhan5735a322022-04-11 17:23:34 +00002499 // Verify targeted injection.
2500 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2501 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002502 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002503 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002504 }
2505
Vishnu Nair062a8672021-09-03 16:07:44 -07002506 // Drop touch events if requested by input feature
2507 if (newTouchedWindowHandle != nullptr &&
2508 shouldDropInput(entry, newTouchedWindowHandle)) {
2509 newTouchedWindowHandle = nullptr;
2510 }
2511
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002512 if (newTouchedWindowHandle != nullptr &&
2513 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002514 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002515 oldTouchedWindowHandle->getName().c_str(),
2516 newTouchedWindowHandle->getName().c_str(), displayId);
2517
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002519 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002520 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002521 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002522
2523 const TouchedWindow& touchedWindow =
2524 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002525 addPointerWindowTargetLocked(oldTouchedWindowHandle,
2526 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
2527 pointerIds,
2528 touchedWindow.getDownTimeInTarget(entry.deviceId),
2529 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530
2531 // Make a slippery entrance into the new window.
2532 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002533 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
2535
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002536 ftl::Flags<InputTarget::Flags> targetFlags =
2537 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002538 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002539 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002542 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002545 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002546 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002547 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002550 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2551 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002552
2553 // Check if the wallpaper window should deliver the corresponding event.
2554 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002555 tempTouchState, entry.deviceId, pointerId, targets);
2556 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2557 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559 }
Arthur Hung96483742022-11-15 03:30:48 +00002560
2561 // Update the pointerIds for non-splittable when it received pointer down.
2562 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2563 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002564 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002565 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2566 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2567 // Ignore drag window for it should just track one pointer.
2568 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2569 continue;
2570 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002571 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2572 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2573 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002574 }
2575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 }
2577
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002578 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002579 {
2580 std::vector<TouchedWindow> hoveringWindows =
2581 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2582 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002583 std::optional<InputTarget> target =
2584 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002585 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002586 if (!target) {
2587 continue;
2588 }
2589 // Hardcode to single hovering pointer for now.
2590 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2591 pointerIds.set(entry.pointerProperties[0].id);
2592 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2593 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596
Prabir Pradhan5735a322022-04-11 17:23:34 +00002597 // Ensure that all touched windows are valid for injection.
2598 if (entry.injectionState != nullptr) {
2599 std::string errs;
2600 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002601 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2602 if (err) errs += "\n - " + *err;
2603 }
2604 if (!errs.empty()) {
2605 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002606 "%s:%s",
2607 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002608 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002609 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002610 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002611 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002612
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002613 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2614 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002616 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002617 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002618 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002619 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002620 for (InputTarget& target : targets) {
2621 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2622 sp<WindowInfoHandle> targetWindow =
2623 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2624 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2625 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 }
2628 }
2629 }
2630 }
2631
Harry Cuttsb166c002023-05-09 13:06:05 +00002632 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2633 // only want the system UI to handle these gestures.
2634 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2635 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2636 if (isTouchpadNavGesture) {
2637 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2638 }
2639
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002640 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002641 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002642 std::bitset<MAX_POINTER_ID + 1> touchingPointers =
2643 touchedWindow.getTouchingPointers(entry.deviceId);
2644 if (touchingPointers.none()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002645 continue;
2646 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002647 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2648 touchingPointers,
2649 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002650 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002651
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002652 // During targeted injection, only allow owned targets to receive events
2653 std::erase_if(targets, [&](const InputTarget& target) {
2654 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2655 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2656 if (err) {
2657 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2658 << ": " << (*err);
2659 return true;
2660 }
2661 return false;
2662 });
2663
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002664 if (targets.empty()) {
2665 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2666 outInjectionResult = InputEventInjectionResult::FAILED;
2667 return {};
2668 }
2669
2670 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2671 // window that is actually receiving the entire gesture.
2672 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2673 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2674 })) {
2675 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2676 << entry.getDescription();
2677 outInjectionResult = InputEventInjectionResult::FAILED;
2678 return {};
2679 }
2680
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002681 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002683 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2684 // Targets that we entered in a slippery way will now become AS-IS targets
2685 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
2686 touchedWindow.targetFlags.clear(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
2687 touchedWindow.targetFlags |= InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002688 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002689 }
2690
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002691 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002692 if (isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002693 if (oldState && oldState->isDown(entry.deviceId)) {
2694 // Started hovering, but the device is already down: reject the hover event
2695 LOG(ERROR) << "Got hover event " << entry.getDescription()
2696 << " but the device is already down " << oldState->dump();
2697 outInjectionResult = InputEventInjectionResult::FAILED;
2698 return {};
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002699 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002700 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2701 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002702 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002703 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002704 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002705 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002706 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2707 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002708 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2709 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2710 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
2712
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002713 // Save changes unless the action was scroll in which case the temporary touch
2714 // state was only valid for this one action.
2715 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002716 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002717 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002718 mTouchStatesByDisplay[displayId] = tempTouchState;
2719 } else {
2720 mTouchStatesByDisplay.erase(displayId);
2721 }
2722 }
2723
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002724 if (tempTouchState.windows.empty()) {
2725 mTouchStatesByDisplay.erase(displayId);
2726 }
2727
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002728 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729}
2730
arthurhung6d4bed92021-03-17 11:59:33 +08002731void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002732 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2733 // have an explicit reason to support it.
2734 constexpr bool isStylus = false;
2735
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002736 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002737 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002738 if (dropWindow) {
2739 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002740 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002741 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002742 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002743 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002744 }
2745 mDragState.reset();
2746}
2747
2748void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002749 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002750 return;
2751 }
2752
arthurhung6d4bed92021-03-17 11:59:33 +08002753 if (!mDragState->isStartDrag) {
2754 mDragState->isStartDrag = true;
2755 mDragState->isStylusButtonDownAtStart =
2756 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2757 }
2758
Arthur Hung54745652022-04-20 07:17:41 +00002759 // Find the pointer index by id.
2760 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002761 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002762 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2763 if (pointerProperties.id == mDragState->pointerId) {
2764 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002765 }
Arthur Hung54745652022-04-20 07:17:41 +00002766 }
arthurhung6d4bed92021-03-17 11:59:33 +08002767
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002768 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002769 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002770 }
2771
2772 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2773 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2774 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2775
2776 switch (maskedAction) {
2777 case AMOTION_EVENT_ACTION_MOVE: {
2778 // Handle the special case : stylus button no longer pressed.
2779 bool isStylusButtonDown =
2780 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2781 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2782 finishDragAndDrop(entry.displayId, x, y);
2783 return;
2784 }
2785
2786 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2787 // until we have an explicit reason to support it.
2788 constexpr bool isStylus = false;
2789
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002790 sp<WindowInfoHandle> hoverWindowHandle =
2791 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2792 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002793 // enqueue drag exit if needed.
2794 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2795 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2796 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002797 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002798 y);
2799 }
2800 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2801 }
2802 // enqueue drag location if needed.
2803 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002804 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002805 }
2806 break;
2807 }
2808
2809 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002810 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002811 break;
2812 }
2813 // The drag pointer is up.
2814 [[fallthrough]];
2815 case AMOTION_EVENT_ACTION_UP:
2816 finishDragAndDrop(entry.displayId, x, y);
2817 break;
2818 case AMOTION_EVENT_ACTION_CANCEL: {
2819 ALOGD("Receiving cancel when drag and drop.");
2820 sendDropWindowCommandLocked(nullptr, 0, 0);
2821 mDragState.reset();
2822 break;
2823 }
arthurhungb89ccb02020-12-30 16:19:01 +08002824 }
2825}
2826
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002827std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2828 const sp<android::gui::WindowInfoHandle>& windowHandle,
2829 ftl::Flags<InputTarget::Flags> targetFlags,
2830 std::optional<nsecs_t> firstDownTimeInTarget) const {
2831 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2832 if (inputChannel == nullptr) {
2833 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2834 return {};
2835 }
2836 InputTarget inputTarget;
2837 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002838 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002839 inputTarget.flags = targetFlags;
2840 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2841 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2842 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2843 if (displayInfoIt != mDisplayInfos.end()) {
2844 inputTarget.displayTransform = displayInfoIt->second.transform;
2845 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002846 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002847 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2848 }
2849 return inputTarget;
2850}
2851
chaviw98318de2021-05-19 16:45:23 -05002852void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002853 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002854 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002855 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002856 std::vector<InputTarget>::iterator it =
2857 std::find_if(inputTargets.begin(), inputTargets.end(),
2858 [&windowHandle](const InputTarget& inputTarget) {
2859 return inputTarget.inputChannel->getConnectionToken() ==
2860 windowHandle->getToken();
2861 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002862
chaviw98318de2021-05-19 16:45:23 -05002863 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002864
2865 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002866 std::optional<InputTarget> target =
2867 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2868 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002869 return;
2870 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002871 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002872 it = inputTargets.end() - 1;
2873 }
2874
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002875 if (it->flags != targetFlags) {
2876 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2877 }
2878 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2879 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2880 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2881 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002882}
2883
2884void InputDispatcher::addPointerWindowTargetLocked(
2885 const sp<android::gui::WindowInfoHandle>& windowHandle,
2886 ftl::Flags<InputTarget::Flags> targetFlags, std::bitset<MAX_POINTER_ID + 1> pointerIds,
2887 std::optional<nsecs_t> firstDownTimeInTarget, std::vector<InputTarget>& inputTargets) const
2888 REQUIRES(mLock) {
2889 if (pointerIds.none()) {
2890 for (const auto& target : inputTargets) {
2891 LOG(INFO) << "Target: " << target;
2892 }
2893 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2894 return;
2895 }
2896 std::vector<InputTarget>::iterator it =
2897 std::find_if(inputTargets.begin(), inputTargets.end(),
2898 [&windowHandle](const InputTarget& inputTarget) {
2899 return inputTarget.inputChannel->getConnectionToken() ==
2900 windowHandle->getToken();
2901 });
2902
2903 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2904 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2905 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2906 // input targets for hovering pointers and for touching pointers.
2907 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2908 // target instead.
2909 if (it != inputTargets.end() && it->flags.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
2910 // Force the code below to create a new input target
2911 it = inputTargets.end();
2912 }
2913
2914 const WindowInfo* windowInfo = windowHandle->getInfo();
2915
2916 if (it == inputTargets.end()) {
2917 std::optional<InputTarget> target =
2918 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2919 if (!target) {
2920 return;
2921 }
2922 inputTargets.push_back(*target);
2923 it = inputTargets.end() - 1;
2924 }
2925
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002926 if (it->flags != targetFlags) {
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002927 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002928 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002929 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2930 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2931 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2932 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002933
chaviw1ff3d1e2020-07-01 15:53:47 -07002934 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935}
2936
Michael Wright3dd60e22019-03-27 22:06:44 +00002937void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002938 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002939 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2940 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002941
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002942 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2943 InputTarget target;
2944 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002945 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002946 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2947 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002948 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2949 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002950 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002951 target.setDefaultPointerTransform(target.displayTransform);
2952 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 }
2954}
2955
Robert Carrc9bf1d32020-04-13 17:21:08 -07002956/**
2957 * Indicate whether one window handle should be considered as obscuring
2958 * another window handle. We only check a few preconditions. Actually
2959 * checking the bounds is left to the caller.
2960 */
chaviw98318de2021-05-19 16:45:23 -05002961static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2962 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002963 // Compare by token so cloned layers aren't counted
2964 if (haveSameToken(windowHandle, otherHandle)) {
2965 return false;
2966 }
2967 auto info = windowHandle->getInfo();
2968 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002969 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002970 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002971 } else if (otherInfo->alpha == 0 &&
2972 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002973 // Those act as if they were invisible, so we don't need to flag them.
2974 // We do want to potentially flag touchable windows even if they have 0
2975 // opacity, since they can consume touches and alter the effects of the
2976 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002977 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002978 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2979 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002980 } else if (info->ownerUid == otherInfo->ownerUid) {
2981 // If ownerUid is the same we don't generate occlusion events as there
2982 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002983 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002984 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002985 return false;
2986 } else if (otherInfo->displayId != info->displayId) {
2987 return false;
2988 }
2989 return true;
2990}
2991
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002992/**
2993 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2994 * untrusted, one should check:
2995 *
2996 * 1. If result.hasBlockingOcclusion is true.
2997 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2998 * BLOCK_UNTRUSTED.
2999 *
3000 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3001 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3002 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3003 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3004 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3005 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3006 *
3007 * If neither of those is true, then it means the touch can be allowed.
3008 */
3009InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003010 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3011 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003012 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003013 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003014 TouchOcclusionInfo info;
3015 info.hasBlockingOcclusion = false;
3016 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003017 info.obscuringUid = gui::Uid::INVALID;
3018 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003019 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003020 if (windowHandle == otherHandle) {
3021 break; // All future windows are below us. Exit early.
3022 }
chaviw98318de2021-05-19 16:45:23 -05003023 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003024 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3025 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003026 if (DEBUG_TOUCH_OCCLUSION) {
3027 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003028 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003029 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003030 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3031 // we perform the checks below to see if the touch can be propagated or not based on the
3032 // window's touch occlusion mode
3033 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3034 info.hasBlockingOcclusion = true;
3035 info.obscuringUid = otherInfo->ownerUid;
3036 info.obscuringPackage = otherInfo->packageName;
3037 break;
3038 }
3039 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003040 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003041 float opacity =
3042 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3043 // Given windows A and B:
3044 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3045 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3046 opacityByUid[uid] = opacity;
3047 if (opacity > info.obscuringOpacity) {
3048 info.obscuringOpacity = opacity;
3049 info.obscuringUid = uid;
3050 info.obscuringPackage = otherInfo->packageName;
3051 }
3052 }
3053 }
3054 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003055 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003056 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003057 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003058 return info;
3059}
3060
chaviw98318de2021-05-19 16:45:23 -05003061std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003062 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003063 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003064 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3065 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3066 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003067 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003068 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003069 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3070 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003071 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3072 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3073 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003074 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003075}
3076
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003077bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3078 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003079 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3080 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003081 return false;
3082 }
3083 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003084 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003085 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003086 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003087 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3088 return false;
3089 }
3090 return true;
3091}
3092
chaviw98318de2021-05-19 16:45:23 -05003093bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003096 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3097 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003098 if (windowHandle == otherHandle) {
3099 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 }
chaviw98318de2021-05-19 16:45:23 -05003101 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003102 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003103 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 return true;
3105 }
3106 }
3107 return false;
3108}
3109
chaviw98318de2021-05-19 16:45:23 -05003110bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003111 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003112 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3113 const WindowInfo* windowInfo = windowHandle->getInfo();
3114 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003115 if (windowHandle == otherHandle) {
3116 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003117 }
chaviw98318de2021-05-19 16:45:23 -05003118 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003119 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003120 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003121 return true;
3122 }
3123 }
3124 return false;
3125}
3126
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003127std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003128 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003129 if (applicationHandle != nullptr) {
3130 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003131 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 } else {
3133 return applicationHandle->getName();
3134 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003135 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003136 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003138 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
3140}
3141
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003142void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003143 if (!isUserActivityEvent(eventEntry)) {
3144 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003145 return;
3146 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003147 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003148 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003149 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003150 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003151 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003152 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003153 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
3155 }
3156
3157 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003158 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003159 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003160 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3161 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 return;
3163 }
Josep del Riob3981622023-04-18 15:49:45 +00003164 if (windowDisablingUserActivityInfo != nullptr) {
3165 if (DEBUG_DISPATCH_CYCLE) {
3166 ALOGD("Not poking user activity: disabled by window '%s'.",
3167 windowDisablingUserActivityInfo->name.c_str());
3168 }
3169 return;
3170 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003171 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 eventType = USER_ACTIVITY_EVENT_TOUCH;
3173 }
3174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003176 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003177 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3178 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 return;
3180 }
Josep del Riob3981622023-04-18 15:49:45 +00003181 // If the key code is unknown, we don't consider it user activity
3182 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3183 return;
3184 }
3185 // Don't inhibit events that were intercepted or are not passed to
3186 // the apps, like system shortcuts
3187 if (windowDisablingUserActivityInfo != nullptr &&
3188 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3189 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3190 if (DEBUG_DISPATCH_CYCLE) {
3191 ALOGD("Not poking user activity: disabled by window '%s'.",
3192 windowDisablingUserActivityInfo->name.c_str());
3193 }
3194 return;
3195 }
3196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 eventType = USER_ACTIVITY_EVENT_BUTTON;
3198 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003200 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003201 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003202 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003203 break;
3204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206
Prabir Pradhancef936d2021-07-21 16:17:52 +00003207 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3208 REQUIRES(mLock) {
3209 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003210 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003211 };
3212 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213}
3214
3215void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003216 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003217 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003218 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003219 ATRACE_NAME_IF(ATRACE_ENABLED(),
3220 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3221 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003222 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003223 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003224 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003225 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003226 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003227 inputTarget.getPointerInfoString().c_str());
3228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229
3230 // Skip this event if the connection status is not normal.
3231 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003232 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003233 if (DEBUG_DISPATCH_CYCLE) {
3234 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003235 connection->getInputChannelName().c_str(),
3236 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 return;
3239 }
3240
3241 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003242 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003243 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003244 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003245 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003247 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003248 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003249 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3250 logDispatchStateLocked();
3251 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3252 "target on connection "
3253 << connection->getInputChannelName() << " for "
3254 << originalMotionEntry.getDescription();
3255 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003257 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3258 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 if (!splitMotionEntry) {
3260 return; // split event was dropped
3261 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003262 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3263 std::string reason = std::string("reason=pointer cancel on split window");
3264 android_log_event_list(LOGTAG_INPUT_CANCEL)
3265 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3266 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003267 if (DEBUG_FOCUS) {
3268 ALOGD("channel '%s' ~ Split motion event.",
3269 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003270 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003271 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003272 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3273 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 return;
3275 }
3276 }
3277
3278 // Not splitting. Enqueue dispatch entries for the event as is.
3279 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3280}
3281
3282void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003283 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003284 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003285 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003286 ATRACE_NAME_IF(ATRACE_ENABLED(),
3287 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3288 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003289 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3290 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003291
hongzuo liu95785e22022-09-06 02:51:35 +00003292 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293
3294 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003295 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003297 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003299 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003300 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003301 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003302 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003303 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003304 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003305 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003306 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
3308 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003309 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 startDispatchCycleLocked(currentTime, connection);
3311 }
3312}
3313
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003314void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003316 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003317 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003318 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3319 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 return;
3321 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322
3323 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3324 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325
3326 // This is a new event.
3327 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003328 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003329 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003331 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3332 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003335 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003336 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003337 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3339 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003340 LOG(WARNING) << "channel " << connection->getInputChannelName()
3341 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 return; // skip the inconsistent event
3343 }
3344 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003347 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003349 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3350 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3351 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3352 static_cast<int32_t>(IdGenerator::Source::OTHER);
3353 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003354 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003356 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003358 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003360 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003362 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3364 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003365 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 }
3367 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003368 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3369 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003370 if (DEBUG_DISPATCH_CYCLE) {
3371 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3372 "enter event",
3373 connection->getInputChannelName().c_str());
3374 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003375 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3376 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003380 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3381 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3382 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003383 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3385 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003386 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003390 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3391 // devices being active at the same time in the same window, so if a new device is
3392 // active, cancel the gesture from the old device.
3393
3394 std::unique_ptr<EventEntry> cancelEvent =
3395 connection->inputState
3396 .cancelConflictingInputStream(motionEntry,
3397 dispatchEntry->resolvedAction);
3398 if (cancelEvent != nullptr) {
3399 LOG(INFO) << "Canceling pointers for device " << motionEntry.deviceId << " in "
3400 << connection->getInputChannelName() << " with event "
3401 << cancelEvent->getDescription();
3402 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3403 createDispatchEntry(inputTarget, std::move(cancelEvent),
3404 InputTarget::Flags::DISPATCH_AS_IS);
3405
3406 // Send these cancel events to the queue before sending the event from the new
3407 // device.
3408 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3409 }
3410
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003411 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3412 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003413 LOG(WARNING) << "channel " << connection->getInputChannelName()
3414 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003415 return; // skip the inconsistent event
3416 }
3417
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003418 dispatchEntry->resolvedEventId =
3419 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3420 ? mIdGenerator.nextId()
3421 : motionEntry.id;
3422 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3423 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3424 ") to MotionEvent(id=0x%" PRIx32 ").",
3425 motionEntry.id, dispatchEntry->resolvedEventId);
3426 ATRACE_NAME(message.c_str());
3427 }
3428
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003429 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3430 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3431 // Skip reporting pointer down outside focus to the policy.
3432 break;
3433 }
3434
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003435 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003436 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437
3438 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003440 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003441 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003442 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3443 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003444 break;
3445 }
Chris Yef59a2f42020-10-16 12:55:26 -07003446 case EventEntry::Type::SENSOR: {
3447 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3448 break;
3449 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003450 case EventEntry::Type::CONFIGURATION_CHANGED:
3451 case EventEntry::Type::DEVICE_RESET: {
3452 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003453 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003454 break;
3455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 }
3457
3458 // Remember that we are waiting for this dispatch to complete.
3459 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003460 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462
3463 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003464 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003465 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003466}
3467
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003468/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003469 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003470 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003471 * The first role is to log input interaction with windows, which helps determine what the user was
3472 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3473 * that user started interacting with launcher window, as well as any other window that received
3474 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3475 * when the set of tokens that received the event changes. It is not logged again as long as the
3476 * user is interacting with the same windows.
3477 *
3478 * The second role is to track input device activity for metrics collection. For each input event,
3479 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3480 * input_interaction logs, the device interaction is reported even when the set of interaction
3481 * tokens do not change.
3482 *
3483 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3484 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003485 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003486void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3487 const std::vector<InputTarget>& targets) {
3488 int32_t deviceId;
3489 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 // Skip ACTION_UP events, and all events other than keys and motions
3491 if (entry.type == EventEntry::Type::KEY) {
3492 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3493 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3494 return;
3495 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003496 deviceId = keyEntry.deviceId;
3497 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003498 } else if (entry.type == EventEntry::Type::MOTION) {
3499 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3500 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003501 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3502 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003503 return;
3504 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003505 deviceId = motionEntry.deviceId;
3506 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003507 } else {
3508 return; // Not a key or a motion
3509 }
3510
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003511 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003512 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003513 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003514 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003515 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003516 continue; // Skip windows that receive ACTION_OUTSIDE
3517 }
3518
3519 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003520 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003521 if (connection == nullptr) {
3522 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003523 }
3524 newConnectionTokens.insert(std::move(token));
3525 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003526 if (target.windowHandle) {
3527 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3528 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003529 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003530
3531 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3532 REQUIRES(mLock) {
3533 scoped_unlock unlock(mLock);
3534 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3535 };
3536 postCommandLocked(std::move(command));
3537
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003538 if (newConnectionTokens == mInteractionConnectionTokens) {
3539 return; // no change
3540 }
3541 mInteractionConnectionTokens = newConnectionTokens;
3542
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003543 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003544 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003545 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003546 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003547 std::string message = "Interaction with: " + targetList;
3548 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003549 message += "<none>";
3550 }
3551 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3552}
3553
chaviwfd6d3512019-03-25 13:23:49 -07003554void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003555 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003556 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003557 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3558 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003559 return;
3560 }
3561
Vishnu Nairc519ff72021-01-21 08:23:08 -08003562 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003563 if (focusedToken == token) {
3564 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003565 return;
3566 }
3567
Prabir Pradhancef936d2021-07-21 16:17:52 +00003568 auto command = [this, token]() REQUIRES(mLock) {
3569 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003570 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003571 };
3572 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573}
3574
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003575status_t InputDispatcher::publishMotionEvent(Connection& connection,
3576 DispatchEntry& dispatchEntry) const {
3577 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3578 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3579
3580 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003581 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003582
3583 // Set the X and Y offset and X and Y scale depending on the input source.
3584 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003585 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003586 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3587 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003588 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003589 scaledCoords[i] = motionEntry.pointerCoords[i];
3590 // Don't apply window scale here since we don't want scale to affect raw
3591 // coordinates. The scale will be sent back to the client and applied
3592 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003593 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003594 }
3595 usingCoords = scaledCoords;
3596 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003597 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003598 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003599 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003600 scaledCoords[i].clear();
3601 }
3602 usingCoords = scaledCoords;
3603 }
3604
3605 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3606
3607 // Publish the motion event.
3608 return connection.inputPublisher
3609 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3610 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3611 std::move(hmac), dispatchEntry.resolvedAction,
3612 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3613 motionEntry.edgeFlags, motionEntry.metaState,
3614 motionEntry.buttonState, motionEntry.classification,
3615 dispatchEntry.transform, motionEntry.xPrecision,
3616 motionEntry.yPrecision, motionEntry.xCursorPosition,
3617 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3618 motionEntry.downTime, motionEntry.eventTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003619 motionEntry.getPointerCount(), motionEntry.pointerProperties.data(),
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003620 usingCoords);
3621}
3622
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003624 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003625 ATRACE_NAME_IF(ATRACE_ENABLED(),
3626 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3627 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003628 if (DEBUG_DISPATCH_CYCLE) {
3629 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003632 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003633 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003635 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003636 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637
3638 // Publish the event.
3639 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003640 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3641 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003642 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003643 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3644 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003645 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003646 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3647 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003650 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003651 status = connection->inputPublisher
3652 .publishKeyEvent(dispatchEntry->seq,
3653 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3654 keyEntry.source, keyEntry.displayId,
3655 std::move(hmac), dispatchEntry->resolvedAction,
3656 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3657 keyEntry.scanCode, keyEntry.metaState,
3658 keyEntry.repeatCount, keyEntry.downTime,
3659 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003663 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003664 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003665 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3666 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003667 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003668 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003669 break;
3670 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003671
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003672 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003673 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003674 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003676 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003677 break;
3678 }
3679
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003680 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3681 const TouchModeEntry& touchModeEntry =
3682 static_cast<const TouchModeEntry&>(eventEntry);
3683 status = connection->inputPublisher
3684 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3685 touchModeEntry.inTouchMode);
3686
3687 break;
3688 }
3689
Prabir Pradhan99987712020-11-10 18:43:05 -08003690 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3691 const auto& captureEntry =
3692 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3693 status = connection->inputPublisher
3694 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003695 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003696 break;
3697 }
3698
arthurhungb89ccb02020-12-30 16:19:01 +08003699 case EventEntry::Type::DRAG: {
3700 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3701 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3702 dragEntry.id, dragEntry.x,
3703 dragEntry.y,
3704 dragEntry.isExiting);
3705 break;
3706 }
3707
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003708 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003709 case EventEntry::Type::DEVICE_RESET:
3710 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003711 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003712 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003713 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716
3717 // Check the result.
3718 if (status) {
3719 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003720 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 "This is unexpected because the wait queue is empty, so the pipe "
3723 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003724 "event to it, status=%s(%d)",
3725 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3726 status);
Harry Cutts33476232023-01-30 19:57:29 +00003727 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 } else {
3729 // Pipe is full and we are waiting for the app to finish process some events
3730 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003731 if (DEBUG_DISPATCH_CYCLE) {
3732 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3733 "waiting for the application to catch up",
3734 connection->getInputChannelName().c_str());
3735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737 } else {
3738 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003739 "status=%s(%d)",
3740 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3741 status);
Harry Cutts33476232023-01-30 19:57:29 +00003742 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 }
3744 return;
3745 }
3746
3747 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003748 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3749 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3750 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003751 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003752 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003753 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003754 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003755 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
3757}
3758
chaviw09c8d2d2020-08-24 15:48:26 -07003759std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3760 size_t size;
3761 switch (event.type) {
3762 case VerifiedInputEvent::Type::KEY: {
3763 size = sizeof(VerifiedKeyEvent);
3764 break;
3765 }
3766 case VerifiedInputEvent::Type::MOTION: {
3767 size = sizeof(VerifiedMotionEvent);
3768 break;
3769 }
3770 }
3771 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3772 return mHmacKeyManager.sign(start, size);
3773}
3774
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003775const std::array<uint8_t, 32> InputDispatcher::getSignature(
3776 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003777 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003778 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003779 // Only sign events up and down events as the purely move events
3780 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003781 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003782 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003783
3784 VerifiedMotionEvent verifiedEvent =
3785 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3786 verifiedEvent.actionMasked = actionMasked;
3787 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3788 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003789}
3790
3791const std::array<uint8_t, 32> InputDispatcher::getSignature(
3792 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3793 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3794 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3795 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003796 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003797}
3798
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003800 const std::shared_ptr<Connection>& connection,
3801 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003802 if (DEBUG_DISPATCH_CYCLE) {
3803 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3804 connection->getInputChannelName().c_str(), seq, toString(handled));
3805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003807 if (connection->status == Connection::Status::BROKEN ||
3808 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 return;
3810 }
3811
3812 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003813 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3814 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3815 };
3816 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817}
3818
3819void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003820 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003822 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003823 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3824 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826
3827 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003828 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003829 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003830 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003831 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
3833 // The connection appears to be unrecoverably broken.
3834 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003835 if (connection->status == Connection::Status::NORMAL) {
3836 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837
3838 if (notify) {
3839 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003840 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3841 connection->getInputChannelName().c_str());
3842
3843 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003844 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003845 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003846 };
3847 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849 }
3850}
3851
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003852void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003853 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003854 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003855 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 }
3857}
3858
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003859void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003861 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863}
3864
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003865int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3866 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003867 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003868 if (connection == nullptr) {
3869 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3870 connectionToken.get(), events);
3871 return 0; // remove the callback
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003874 bool notify;
3875 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3876 if (!(events & ALOOPER_EVENT_INPUT)) {
3877 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3878 "events=0x%x",
3879 connection->getInputChannelName().c_str(), events);
3880 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 }
3882
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003883 nsecs_t currentTime = now();
3884 bool gotOne = false;
3885 status_t status = OK;
3886 for (;;) {
3887 Result<InputPublisher::ConsumerResponse> result =
3888 connection->inputPublisher.receiveConsumerResponse();
3889 if (!result.ok()) {
3890 status = result.error().code();
3891 break;
3892 }
3893
3894 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3895 const InputPublisher::Finished& finish =
3896 std::get<InputPublisher::Finished>(*result);
3897 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3898 finish.consumeTime);
3899 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003900 if (shouldReportMetricsForConnection(*connection)) {
3901 const InputPublisher::Timeline& timeline =
3902 std::get<InputPublisher::Timeline>(*result);
3903 mLatencyTracker
3904 .trackGraphicsLatency(timeline.inputEventId,
3905 connection->inputChannel->getConnectionToken(),
3906 std::move(timeline.graphicsTimeline));
3907 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003908 }
3909 gotOne = true;
3910 }
3911 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003912 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003913 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 return 1;
3915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 }
3917
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003918 notify = status != DEAD_OBJECT || !connection->monitor;
3919 if (notify) {
3920 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3921 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3922 status);
3923 }
3924 } else {
3925 // Monitor channels are never explicitly unregistered.
3926 // We do it automatically when the remote endpoint is closed so don't warn about them.
3927 const bool stillHaveWindowHandle =
3928 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3929 notify = !connection->monitor && stillHaveWindowHandle;
3930 if (notify) {
3931 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3932 connection->getInputChannelName().c_str(), events);
3933 }
3934 }
3935
3936 // Remove the channel.
3937 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3938 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939}
3940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003943 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003944 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
3946}
3947
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003948void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003949 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003950 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003951 for (const Monitor& monitor : monitors) {
3952 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003953 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003954 }
3955}
3956
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003958 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003959 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003960 if (connection == nullptr) {
3961 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003963
3964 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965}
3966
3967void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003968 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li5af92f92023-07-14 14:36:22 +08003969 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3970 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3971 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3972 LOG(INFO) << __func__
3973 << ": Canceling drag and drop because the pointers for the drag window are being "
3974 "canceled.";
3975 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3976 mDragState.reset();
3977 }
3978
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003979 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 return;
3981 }
3982
3983 nsecs_t currentTime = now();
3984
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003985 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003986 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003988 if (cancelationEvents.empty()) {
3989 return;
3990 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003991 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3992 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003993 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003994 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003995 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003996 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003997
Arthur Hungb3307ee2021-10-14 10:57:37 +00003998 std::string reason = std::string("reason=").append(options.reason);
3999 android_log_event_list(LOGTAG_INPUT_CANCEL)
4000 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4001
hongzuo liu95785e22022-09-06 02:51:35 +00004002 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004003 // The target to use if we don't find a window associated with the channel.
4004 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
4005 .flags = InputTarget::Flags::DISPATCH_AS_IS};
4006 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004007
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004008 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004009 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004010 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004011
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004012 switch (cancelationEventEntry->type) {
4013 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004014 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004015 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4016 ? std::make_optional(keyEntry.displayId)
4017 : std::nullopt;
4018 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
4019 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004020 keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004021 } else {
4022 targets.emplace_back(fallbackTarget);
4023 }
4024 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004025 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004027 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004028 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004029 const std::optional<int32_t> targetDisplay =
4030 motionEntry.displayId != ADISPLAY_ID_NONE
4031 ? std::make_optional(motionEntry.displayId)
4032 : std::nullopt;
4033 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004034 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004035 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004036 pointerIndex++) {
4037 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4038 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004039 addPointerWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
4040 pointerIds, motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004041 } else {
4042 targets.emplace_back(fallbackTarget);
4043 const auto it = mDisplayInfos.find(motionEntry.displayId);
4044 if (it != mDisplayInfos.end()) {
4045 targets.back().displayTransform = it->second.transform;
4046 targets.back().setDefaultPointerTransform(it->second.transform);
4047 }
4048 }
4049 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004050 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004052 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004053 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004054 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4055 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004056 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004057 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004058 break;
4059 }
4060 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004061 case EventEntry::Type::DEVICE_RESET:
4062 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004063 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004064 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004065 break;
4066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 }
4068
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004069 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4070 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004071 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004073
hongzuo liu95785e22022-09-06 02:51:35 +00004074 // If the outbound queue was previously empty, start the dispatch cycle going.
4075 if (wasEmpty && !connection->outboundQueue.empty()) {
4076 startDispatchCycleLocked(currentTime, connection);
4077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078}
4079
Svet Ganov5d3bc372020-01-26 23:11:07 -08004080void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004081 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004082 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004083 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004084 return;
4085 }
4086
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004087 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004088 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004089
4090 if (downEvents.empty()) {
4091 return;
4092 }
4093
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004094 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004095 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4096 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004097 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004098
chaviw98318de2021-05-19 16:45:23 -05004099 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004100 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004101
hongzuo liu95785e22022-09-06 02:51:35 +00004102 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004103 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004104 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004105 switch (downEventEntry->type) {
4106 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004107 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4108 if (windowHandle != nullptr) {
4109 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004110 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004111 pointerIndex++) {
4112 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4113 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07004114 addPointerWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4115 motionEntry.downTime, targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004116 } else {
4117 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4118 .flags = targetFlags});
4119 const auto it = mDisplayInfos.find(motionEntry.displayId);
4120 if (it != mDisplayInfos.end()) {
4121 targets.back().displayTransform = it->second.transform;
4122 targets.back().setDefaultPointerTransform(it->second.transform);
4123 }
4124 }
4125 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004126 break;
4127 }
4128
4129 case EventEntry::Type::KEY:
4130 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004131 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004132 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004133 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004134 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004135 case EventEntry::Type::SENSOR:
4136 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004137 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004138 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004139 break;
4140 }
4141 }
4142
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004143 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4144 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004145 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004146 }
4147
hongzuo liu95785e22022-09-06 02:51:35 +00004148 // If the outbound queue was previously empty, start the dispatch cycle going.
4149 if (wasEmpty && !connection->outboundQueue.empty()) {
4150 startDispatchCycleLocked(downTime, connection);
4151 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004152}
4153
Arthur Hungc539dbb2022-12-08 07:45:36 +00004154void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4155 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4156 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004157 std::shared_ptr<Connection> wallpaperConnection =
4158 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004159 if (wallpaperConnection != nullptr) {
4160 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4161 }
4162 }
4163}
4164
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004165std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004166 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4167 nsecs_t splitDownTime) {
4168 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169
4170 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004171 std::vector<PointerProperties> splitPointerProperties;
4172 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004174 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 uint32_t splitPointerCount = 0;
4176
4177 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004180 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004182 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004184 splitPointerProperties.push_back(pointerProperties);
4185 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 splitPointerCount += 1;
4187 }
4188 }
4189
4190 if (splitPointerCount != pointerIds.count()) {
4191 // This is bad. We are missing some of the pointers that we expected to deliver.
4192 // Most likely this indicates that we received an ACTION_MOVE events that has
4193 // different pointer ids than we expected based on the previous ACTION_DOWN
4194 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4195 // in this way.
4196 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004197 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004198 "a broken sequence of pointer ids from the input device: %s",
4199 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004200 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 }
4202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004203 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4206 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004207 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004209 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004211 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 if (pointerIds.count() == 1) {
4213 // The first/last pointer went down/up.
4214 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004216 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4217 ? AMOTION_EVENT_ACTION_CANCEL
4218 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 } else {
4220 // A secondary pointer went down/up.
4221 uint32_t splitPointerIndex = 0;
4222 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4223 splitPointerIndex += 1;
4224 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 action = maskedAction |
4226 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228 } else {
4229 // An unrelated pointer changed.
4230 action = AMOTION_EVENT_ACTION_MOVE;
4231 }
4232 }
4233
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004234 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4235 logDispatchStateLocked();
4236 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4237 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4238 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004239 }
4240
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004241 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004242 ATRACE_NAME_IF(ATRACE_ENABLED(),
4243 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4244 ").",
4245 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004246 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004247 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4248 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004249 originalMotionEntry.deviceId, originalMotionEntry.source,
4250 originalMotionEntry.displayId,
4251 originalMotionEntry.policyFlags, action,
4252 originalMotionEntry.actionButton,
4253 originalMotionEntry.flags, originalMotionEntry.metaState,
4254 originalMotionEntry.buttonState,
4255 originalMotionEntry.classification,
4256 originalMotionEntry.edgeFlags,
4257 originalMotionEntry.xPrecision,
4258 originalMotionEntry.yPrecision,
4259 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004260 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004261 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 return splitMotionEntry;
4264}
4265
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004266void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4267 std::scoped_lock _l(mLock);
4268 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4269}
4270
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004271void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004272 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004273 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
Antonio Kantekf16f2832021-09-28 04:39:20 +00004276 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004278 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004280 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004281 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 } // release lock
4284
4285 if (needWake) {
4286 mLooper->wake();
4287 }
4288}
4289
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004290void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004291 ALOGD_IF(debugInboundEventDetails(),
4292 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4293 ", deviceId=%d, source=%s, displayId=%" PRId32
4294 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4295 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004296 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4297 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4298 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004299 Result<void> keyCheck = validateKeyEvent(args.action);
4300 if (!keyCheck.ok()) {
4301 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 return;
4303 }
4304
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004305 uint32_t policyFlags = args.policyFlags;
4306 int32_t flags = args.flags;
4307 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004308 // InputDispatcher tracks and generates key repeats on behalf of
4309 // whatever notifies it, so repeatCount should always be set to 0
4310 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4312 policyFlags |= POLICY_FLAG_VIRTUAL;
4313 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 if (policyFlags & POLICY_FLAG_FUNCTION) {
4316 metaState |= AMETA_FUNCTION_ON;
4317 }
4318
4319 policyFlags |= POLICY_FLAG_TRUSTED;
4320
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004321 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004323 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4324 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4325 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Michael Wright2b3c3302018-03-02 17:19:13 +00004327 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004328 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004329 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4330 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
Antonio Kantekf16f2832021-09-28 04:39:20 +00004334 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 { // acquire lock
4336 mLock.lock();
4337
4338 if (shouldSendKeyToInputFilterLocked(args)) {
4339 mLock.unlock();
4340
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004341 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004342 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 return; // event was consumed by the filter
4344 }
4345
4346 mLock.lock();
4347 }
4348
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004350 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4351 args.deviceId, args.source, args.displayId, policyFlags,
4352 args.action, flags, keyCode, args.scanCode, metaState,
4353 repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004355 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 mLock.unlock();
4357 } // release lock
4358
4359 if (needWake) {
4360 mLooper->wake();
4361 }
4362}
4363
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004364bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 return mInputFilterEnabled;
4366}
4367
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004368void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004369 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004370 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004371 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004372 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004373 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4374 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004375 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4376 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4377 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4378 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4379 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004380 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004381 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4382 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004383 i, args.pointerProperties[i].id,
4384 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4385 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4386 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4387 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4388 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4389 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4390 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4391 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4392 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4393 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004396
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004397 Result<void> motionCheck =
4398 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4399 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004400 if (!motionCheck.ok()) {
4401 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4402 return;
4403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004405 if (DEBUG_VERIFY_EVENTS) {
4406 auto [it, _] =
4407 mVerifiersByDisplay.try_emplace(args.displayId,
4408 StringPrintf("display %" PRId32, args.displayId));
4409 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004410 it->second.processMovement(args.deviceId, args.source, args.action,
4411 args.getPointerCount(), args.pointerProperties.data(),
4412 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004413 if (!result.ok()) {
4414 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4415 }
4416 }
4417
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004418 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004420
4421 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004422 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004423 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4424 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004425 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427
Antonio Kantekf16f2832021-09-28 04:39:20 +00004428 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 { // acquire lock
4430 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004431 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4432 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4433 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004434 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004435 if (touchStateIt != mTouchStatesByDisplay.end()) {
4436 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004437 if (touchState.hasTouchingPointers(args.deviceId) ||
4438 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004439 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4440 }
4441 }
4442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443
4444 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004445 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004446 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004447 displayTransform = it->second.transform;
4448 }
4449
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 mLock.unlock();
4451
4452 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004453 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4454 args.action, args.actionButton, args.flags, args.edgeFlags,
4455 args.metaState, args.buttonState, args.classification,
4456 displayTransform, args.xPrecision, args.yPrecision,
4457 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004458 args.downTime, args.eventTime, args.getPointerCount(),
4459 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
4461 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004462 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 return; // event was consumed by the filter
4464 }
4465
4466 mLock.lock();
4467 }
4468
4469 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004470 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004471 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4472 args.deviceId, args.source, args.displayId,
4473 policyFlags, args.action, args.actionButton,
4474 args.flags, args.metaState, args.buttonState,
4475 args.classification, args.edgeFlags, args.xPrecision,
4476 args.yPrecision, args.xCursorPosition,
4477 args.yCursorPosition, args.downTime,
4478 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004480 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4481 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004482 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004484 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4485 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4486 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004487 }
4488
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004489 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 mLock.unlock();
4491 } // release lock
4492
4493 if (needWake) {
4494 mLooper->wake();
4495 }
4496}
4497
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004498void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004499 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004500 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4501 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004502 args.id, args.eventTime, args.deviceId, args.source,
4503 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004504 }
Chris Yef59a2f42020-10-16 12:55:26 -07004505
Antonio Kantekf16f2832021-09-28 04:39:20 +00004506 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004507 { // acquire lock
4508 mLock.lock();
4509
4510 // Just enqueue a new sensor event.
4511 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004512 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4513 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4514 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004515
4516 needWake = enqueueInboundEventLocked(std::move(newEntry));
4517 mLock.unlock();
4518 } // release lock
4519
4520 if (needWake) {
4521 mLooper->wake();
4522 }
4523}
4524
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004525void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004526 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004527 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4528 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004529 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004530 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004531}
4532
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004533bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004534 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535}
4536
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004537void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004538 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004539 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4540 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004541 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004544 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004546 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547}
4548
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004549void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Siarhei Vishniakou96e4fad2023-09-20 09:30:44 -07004550 // TODO(b/308677868) Remove device reset from the InputListener interface
Prabir Pradhan65613802023-02-22 23:36:58 +00004551 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004552 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4553 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555
Antonio Kantekf16f2832021-09-28 04:39:20 +00004556 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004558 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004560 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004561 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004562 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004563
4564 for (auto& [_, verifier] : mVerifiersByDisplay) {
4565 verifier.resetDevice(args.deviceId);
4566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 } // release lock
4568
4569 if (needWake) {
4570 mLooper->wake();
4571 }
4572}
4573
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004574void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004575 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4577 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004578 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004579
Antonio Kantekf16f2832021-09-28 04:39:20 +00004580 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004581 { // acquire lock
4582 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004583 auto entry =
4584 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004585 needWake = enqueueInboundEventLocked(std::move(entry));
4586 } // release lock
4587
4588 if (needWake) {
4589 mLooper->wake();
4590 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004591}
4592
Prabir Pradhan5735a322022-04-11 17:23:34 +00004593InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004594 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004595 InputEventInjectionSync syncMode,
4596 std::chrono::milliseconds timeout,
4597 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004598 Result<void> eventValidation = validateInputEvent(*event);
4599 if (!eventValidation.ok()) {
4600 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4601 return InputEventInjectionResult::FAILED;
4602 }
4603
Prabir Pradhan65613802023-02-22 23:36:58 +00004604 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004605 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4606 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4607 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4608 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004609 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004610 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611
Prabir Pradhan5735a322022-04-11 17:23:34 +00004612 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004614 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004615 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4616 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4617 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4618 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4619 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004620 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004621 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004622 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004623 }
4624
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004625 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4626 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004628 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004630 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004631 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004632 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004633 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004634 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4635 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4636 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004637 int32_t keyCode = incomingKey.getKeyCode();
4638 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004639 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004640 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004641 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4642 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4643 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004645 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4646 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004647 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648
4649 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4650 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004651 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4653 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4654 std::to_string(t.duration().count()).c_str());
4655 }
4656 }
4657
4658 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004659 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004660 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4661 incomingKey.getEventTime(), resolvedDeviceId,
4662 incomingKey.getSource(), incomingKey.getDisplayId(),
4663 policyFlags, action, flags, keyCode,
4664 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004665 incomingKey.getRepeatCount(),
4666 incomingKey.getDownTime());
4667 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004668 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 }
4670
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004671 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004672 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004673 const bool isPointerEvent =
4674 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4675 // If a pointer event has no displayId specified, inject it to the default display.
4676 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4677 ? ADISPLAY_ID_DEFAULT
4678 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004679 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680
4681 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004682 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004683 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004684 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4686 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4687 std::to_string(t.duration().count()).c_str());
4688 }
4689 }
4690
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004691 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4692 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4693 }
4694
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004695 mLock.lock();
Siarhei Vishniakou96e4fad2023-09-20 09:30:44 -07004696
4697 if (policyFlags & POLICY_FLAG_FILTERED) {
4698 // The events from InputFilter impersonate real hardware devices. Check these
4699 // events for consistency and print an error. An inconsistent event sent from
4700 // InputFilter could cause a crash in the later stages of dispatching pipeline.
4701 auto [it, _] =
4702 mInputFilterVerifiersByDisplay
4703 .try_emplace(displayId,
4704 StringPrintf("Injection on %" PRId32, displayId));
4705 InputVerifier& verifier = it->second;
4706
4707 Result<void> result =
4708 verifier.processMovement(resolvedDeviceId, motionEvent.getSource(),
4709 motionEvent.getAction(),
4710 motionEvent.getPointerCount(),
4711 motionEvent.getPointerProperties(),
4712 motionEvent.getSamplePointerCoords(), flags);
4713 if (!result.ok()) {
4714 logDispatchStateLocked();
4715 LOG(ERROR) << "Inconsistent event: " << motionEvent
4716 << ", reason: " << result.error();
4717 }
4718 }
4719
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004720 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004721 const size_t pointerCount = motionEvent.getPointerCount();
4722 const std::vector<PointerProperties>
4723 pointerProperties(motionEvent.getPointerProperties(),
4724 motionEvent.getPointerProperties() + pointerCount);
4725
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004726 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004727 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004728 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4729 *sampleEventTimes, resolvedDeviceId,
4730 motionEvent.getSource(), displayId, policyFlags,
4731 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004732 motionEvent.getActionButton(), flags,
4733 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004734 motionEvent.getButtonState(),
4735 motionEvent.getClassification(),
4736 motionEvent.getEdgeFlags(),
4737 motionEvent.getXPrecision(),
4738 motionEvent.getYPrecision(),
4739 motionEvent.getRawXCursorPosition(),
4740 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004741 motionEvent.getDownTime(), pointerProperties,
4742 std::vector<PointerCoords>(samplePointerCoords,
4743 samplePointerCoords +
4744 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004745 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004746 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004747 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004749 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004750 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004751 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4752 resolvedDeviceId, motionEvent.getSource(), displayId,
4753 policyFlags, motionEvent.getAction(),
4754 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004755 motionEvent.getMetaState(), motionEvent.getButtonState(),
4756 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4757 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4758 motionEvent.getRawXCursorPosition(),
4759 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4760 pointerProperties,
4761 std::vector<PointerCoords>(samplePointerCoords,
4762 samplePointerCoords +
4763 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004764 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4765 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004766 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004767 }
4768 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004772 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004773 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 }
4775
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004777 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004778 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004779 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004780 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004782 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
4784
4785 mLock.unlock();
4786
4787 if (needWake) {
4788 mLooper->wake();
4789 }
4790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004793 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004795 if (syncMode == InputEventInjectionSync::NONE) {
4796 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 } else {
4798 for (;;) {
4799 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 break;
4802 }
4803
4804 nsecs_t remainingTimeout = endTime - now();
4805 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004806 if (DEBUG_INJECTION) {
4807 ALOGD("injectInputEvent - Timed out waiting for injection result "
4808 "to become available.");
4809 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004810 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 break;
4812 }
4813
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004814 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 }
4816
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004817 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4818 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004820 if (DEBUG_INJECTION) {
4821 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4822 injectionState->pendingForegroundDispatches);
4823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 nsecs_t remainingTimeout = endTime - now();
4825 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004826 if (DEBUG_INJECTION) {
4827 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4828 "dispatches to finish.");
4829 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004830 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 break;
4832 }
4833
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004834 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
4836 }
4837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 } // release lock
4839
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004840 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004841 LOG(INFO) << "injectInputEvent - Finished with result "
4842 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844
4845 return injectionResult;
4846}
4847
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004848std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004849 std::array<uint8_t, 32> calculatedHmac;
4850 std::unique_ptr<VerifiedInputEvent> result;
4851 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004852 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004853 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4854 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4855 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004856 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004857 break;
4858 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004859 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004860 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4861 VerifiedMotionEvent verifiedMotionEvent =
4862 verifiedMotionEventFromMotionEvent(motionEvent);
4863 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004864 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004865 break;
4866 }
4867 default: {
4868 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4869 return nullptr;
4870 }
4871 }
4872 if (calculatedHmac == INVALID_HMAC) {
4873 return nullptr;
4874 }
tyiu1573a672023-02-21 22:38:32 +00004875 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004876 return nullptr;
4877 }
4878 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004879}
4880
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004881void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004882 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004883 if (!entry.injectionState) {
4884 // Not an injected event.
4885 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004887
4888 InjectionState& injectionState = *entry.injectionState;
4889 if (DEBUG_INJECTION) {
4890 LOG(INFO) << "Setting input event injection result to "
4891 << ftl::enum_string(injectionResult);
4892 }
4893
4894 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4895 // Log the outcome since the injector did not wait for the injection result.
4896 switch (injectionResult) {
4897 case InputEventInjectionResult::SUCCEEDED:
4898 ALOGV("Asynchronous input event injection succeeded.");
4899 break;
4900 case InputEventInjectionResult::TARGET_MISMATCH:
4901 ALOGV("Asynchronous input event injection target mismatch.");
4902 break;
4903 case InputEventInjectionResult::FAILED:
4904 ALOGW("Asynchronous input event injection failed.");
4905 break;
4906 case InputEventInjectionResult::TIMED_OUT:
4907 ALOGW("Asynchronous input event injection timed out.");
4908 break;
4909 case InputEventInjectionResult::PENDING:
4910 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4911 break;
4912 }
4913 }
4914
4915 injectionState.injectionResult = injectionResult;
4916 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917}
4918
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004919void InputDispatcher::transformMotionEntryForInjectionLocked(
4920 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004921 // Input injection works in the logical display coordinate space, but the input pipeline works
4922 // display space, so we need to transform the injected events accordingly.
4923 const auto it = mDisplayInfos.find(entry.displayId);
4924 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004925 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004926
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004927 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4928 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4929 const vec2 cursor =
4930 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4931 {entry.xCursorPosition, entry.yCursorPosition});
4932 entry.xCursorPosition = cursor.x;
4933 entry.yCursorPosition = cursor.y;
4934 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004935 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004936 entry.pointerCoords[i] =
4937 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4938 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004939 }
4940}
4941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004942void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004943 if (entry.injectionState) {
4944 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 }
4946}
4947
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004948void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004949 if (entry.injectionState) {
4950 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004952 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004953 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 }
4955 }
4956}
4957
chaviw98318de2021-05-19 16:45:23 -05004958const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004959 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004960 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004961 auto it = mWindowHandlesByDisplay.find(displayId);
4962 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004963}
4964
chaviw98318de2021-05-19 16:45:23 -05004965sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004966 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004967 if (windowHandleToken == nullptr) {
4968 return nullptr;
4969 }
4970
Prabir Pradhan16463382023-10-12 23:03:19 +00004971 if (!displayId) {
4972 // Look through all displays.
4973 for (auto& it : mWindowHandlesByDisplay) {
4974 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4975 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4976 if (windowHandle->getToken() == windowHandleToken) {
4977 return windowHandle;
4978 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004981 return nullptr;
4982 }
4983
Prabir Pradhan16463382023-10-12 23:03:19 +00004984 // Only look through the requested display.
4985 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004986 if (windowHandle->getToken() == windowHandleToken) {
4987 return windowHandle;
4988 }
4989 }
4990 return nullptr;
4991}
4992
chaviw98318de2021-05-19 16:45:23 -05004993sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4994 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004995 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004996 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4997 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004998 if (handle->getId() == windowHandle->getId() &&
4999 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005000 if (windowHandle->getInfo()->displayId != it.first) {
5001 ALOGE("Found window %s in display %" PRId32
5002 ", but it should belong to display %" PRId32,
5003 windowHandle->getName().c_str(), it.first,
5004 windowHandle->getInfo()->displayId);
5005 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005006 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005010 return nullptr;
5011}
5012
chaviw98318de2021-05-19 16:45:23 -05005013sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005014 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5015 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016}
5017
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005018ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5019 auto displayInfoIt = mDisplayInfos.find(displayId);
5020 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5021 : kIdentityTransform;
5022}
5023
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005024bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5025 const MotionEntry& motionEntry) const {
5026 const WindowInfo& info = *window->getInfo();
5027
5028 // Skip spy window targets that are not valid for targeted injection.
5029 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005030 return false;
5031 }
5032
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005033 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5034 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5035 return false;
5036 }
5037
5038 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5039 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5040 window->getName().c_str());
5041 return false;
5042 }
5043
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005044 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005045 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005046 ALOGW("Not sending touch to %s because there's no corresponding connection",
5047 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005048 return false;
5049 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005050
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005051 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005052 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005053 return false;
5054 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005055
5056 // Drop events that can't be trusted due to occlusion
5057 const auto [x, y] = resolveTouchedPosition(motionEntry);
5058 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5059 if (!isTouchTrustedLocked(occlusionInfo)) {
5060 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005061 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005062 for (const auto& log : occlusionInfo.debugInfo) {
5063 ALOGD("%s", log.c_str());
5064 }
5065 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005066 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5067 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005068 return false;
5069 }
5070
5071 // Drop touch events if requested by input feature
5072 if (shouldDropInput(motionEntry, window)) {
5073 return false;
5074 }
5075
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005076 return true;
5077}
5078
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005079std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5080 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005081 auto connectionIt = mConnectionsByToken.find(token);
5082 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005083 return nullptr;
5084 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005085 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005086}
5087
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005088void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005089 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5090 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005091 // Remove all handles on a display if there are no windows left.
5092 mWindowHandlesByDisplay.erase(displayId);
5093 return;
5094 }
5095
5096 // Since we compare the pointer of input window handles across window updates, we need
5097 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005098 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5099 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5100 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005101 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005102 }
5103
chaviw98318de2021-05-19 16:45:23 -05005104 std::vector<sp<WindowInfoHandle>> newHandles;
5105 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005106 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005107 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005108 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005109 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005110 const bool canReceiveInput =
5111 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5112 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005113 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005114 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005115 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005116 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005117 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005118 }
5119
5120 if (info->displayId != displayId) {
5121 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5122 handle->getName().c_str(), displayId, info->displayId);
5123 continue;
5124 }
5125
Robert Carredd13602020-04-13 17:24:34 -07005126 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5127 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005128 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005129 oldHandle->updateFrom(handle);
5130 newHandles.push_back(oldHandle);
5131 } else {
5132 newHandles.push_back(handle);
5133 }
5134 }
5135
5136 // Insert or replace
5137 mWindowHandlesByDisplay[displayId] = newHandles;
5138}
5139
Arthur Hungb92218b2018-08-14 12:00:21 +08005140/**
5141 * Called from InputManagerService, update window handle list by displayId that can receive input.
5142 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5143 * If set an empty list, remove all handles from the specific display.
5144 * For focused handle, check if need to change and send a cancel event to previous one.
5145 * For removed handle, check if need to send a cancel event if already in touch.
5146 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005148 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 if (DEBUG_FOCUS) {
5150 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005151 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005152 windowList += iwh->getName() + " ";
5153 }
5154 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156
Prabir Pradhand65552b2021-10-07 11:23:50 -07005157 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005158 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005159 const WindowInfo& info = *window->getInfo();
5160
5161 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005162 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005163 if (noInputWindow && window->getToken() != nullptr) {
5164 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5165 window->getName().c_str());
5166 window->releaseChannel();
5167 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005168
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005169 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005170 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5171 !info.inputConfig.test(
5172 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005173 "%s has feature SPY, but is not a trusted overlay.",
5174 window->getName().c_str());
5175
Prabir Pradhand65552b2021-10-07 11:23:50 -07005176 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005177 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5178 !info.inputConfig.test(
5179 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005180 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5181 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005182 }
5183
Arthur Hung72d8dc32020-03-28 00:48:39 +00005184 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005185 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186
chaviw98318de2021-05-19 16:45:23 -05005187 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005188
chaviw98318de2021-05-19 16:45:23 -05005189 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005190
Vishnu Nairc519ff72021-01-21 08:23:08 -08005191 std::optional<FocusResolver::FocusChanges> changes =
5192 mFocusResolver.setInputWindows(displayId, windowHandles);
5193 if (changes) {
5194 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005197 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5198 mTouchStatesByDisplay.find(displayId);
5199 if (stateIt != mTouchStatesByDisplay.end()) {
5200 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005201 for (size_t i = 0; i < state.windows.size();) {
5202 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005203 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005204 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5205 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005206 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005207 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5208 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005209 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005210 "touched window was removed");
5211 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005212 // Since we are about to drop the touch, cancel the events for the wallpaper as
5213 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005214 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005215 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5216 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005217 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005218 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005221 state.windows.erase(state.windows.begin() + i);
5222 } else {
5223 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 }
5225 }
arthurhungb89ccb02020-12-30 16:19:01 +08005226
arthurhung6d4bed92021-03-17 11:59:33 +08005227 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005228 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005229 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005230 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005231 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005232 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5233 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005234 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005235 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005236 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005237
Arthur Hung72d8dc32020-03-28 00:48:39 +00005238 // Release information for windows that are no longer present.
5239 // This ensures that unused input channels are released promptly.
5240 // Otherwise, they might stick around until the window handle is destroyed
5241 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005242 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005243 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005244 if (DEBUG_FOCUS) {
5245 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005246 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005247 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005248 }
chaviw291d88a2019-02-14 10:33:58 -08005249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250}
5251
5252void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005253 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005254 if (DEBUG_FOCUS) {
5255 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5256 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5257 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005258 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005259 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005260 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 } // release lock
5262
5263 // Wake up poll loop since it may need to make new input dispatching choices.
5264 mLooper->wake();
5265}
5266
Vishnu Nair599f1412021-06-21 10:39:58 -07005267void InputDispatcher::setFocusedApplicationLocked(
5268 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5269 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5270 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5271
5272 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5273 return; // This application is already focused. No need to wake up or change anything.
5274 }
5275
5276 // Set the new application handle.
5277 if (inputApplicationHandle != nullptr) {
5278 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5279 } else {
5280 mFocusedApplicationHandlesByDisplay.erase(displayId);
5281 }
5282
5283 // No matter what the old focused application was, stop waiting on it because it is
5284 // no longer focused.
5285 resetNoFocusedWindowTimeoutLocked();
5286}
5287
Tiger Huang721e26f2018-07-24 22:26:19 +08005288/**
5289 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5290 * the display not specified.
5291 *
5292 * We track any unreleased events for each window. If a window loses the ability to receive the
5293 * released event, we will send a cancel event to it. So when the focused display is changed, we
5294 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5295 * display. The display-specified events won't be affected.
5296 */
5297void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005298 if (DEBUG_FOCUS) {
5299 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5300 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005302 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005303
5304 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005305 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005306 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005307 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005308 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005309 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005310 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005311 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005312 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005313 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005314 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005315 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5316 }
5317 }
5318 mFocusedDisplayId = displayId;
5319
Chris Ye3c2d6f52020-08-09 10:39:48 -07005320 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005321 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005322 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005323
Vishnu Nairad321cd2020-08-20 16:40:21 -07005324 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005325 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005326 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005327 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005328 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005329 }
5330 }
5331 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005332 } // release lock
5333
5334 // Wake up poll loop since it may need to make new input dispatching choices.
5335 mLooper->wake();
5336}
5337
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005339 if (DEBUG_FOCUS) {
5340 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342
5343 bool changed;
5344 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346
5347 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5348 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005349 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 }
5351
5352 if (mDispatchEnabled && !enabled) {
5353 resetAndDropEverythingLocked("dispatcher is being disabled");
5354 }
5355
5356 mDispatchEnabled = enabled;
5357 mDispatchFrozen = frozen;
5358 changed = true;
5359 } else {
5360 changed = false;
5361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 } // release lock
5363
5364 if (changed) {
5365 // Wake up poll loop since it may need to make new input dispatching choices.
5366 mLooper->wake();
5367 }
5368}
5369
5370void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005371 if (DEBUG_FOCUS) {
5372 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374
5375 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377
5378 if (mInputFilterEnabled == enabled) {
5379 return;
5380 }
5381
5382 mInputFilterEnabled = enabled;
5383 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5384 } // release lock
5385
5386 // Wake up poll loop since there might be work to do to drop everything.
5387 mLooper->wake();
5388}
5389
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005390bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005391 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005392 bool needWake = false;
5393 {
5394 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005395 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005396 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005397 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005398 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5399 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005400 mTouchModePerDisplay.count(displayId) == 0
5401 ? "not set"
5402 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5403
Antonio Kantek15beb512022-06-13 22:35:41 +00005404 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5405 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005406 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005407 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005408 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005409 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5410 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005411 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005412 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005413 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005414 return false;
5415 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005416 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005417 mTouchModePerDisplay[displayId] = inTouchMode;
5418 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5419 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005420 needWake = enqueueInboundEventLocked(std::move(entry));
5421 } // release lock
5422
5423 if (needWake) {
5424 mLooper->wake();
5425 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005426 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005427}
5428
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005429bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005430 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5431 if (focusedToken == nullptr) {
5432 return false;
5433 }
5434 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5435 return isWindowOwnedBy(windowHandle, pid, uid);
5436}
5437
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005438bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005439 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5440 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5441 const sp<WindowInfoHandle> windowHandle =
5442 getWindowHandleLocked(connectionToken);
5443 return isWindowOwnedBy(windowHandle, pid, uid);
5444 }) != mInteractionConnectionTokens.end();
5445}
5446
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005447void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5448 if (opacity < 0 || opacity > 1) {
5449 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5450 return;
5451 }
5452
5453 std::scoped_lock lock(mLock);
5454 mMaximumObscuringOpacityForTouch = opacity;
5455}
5456
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005457std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5458InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5460 for (TouchedWindow& w : state.windows) {
5461 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005462 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005463 }
5464 }
5465 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005466 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005467}
5468
arthurhungb89ccb02020-12-30 16:19:01 +08005469bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5470 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005471 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005472 if (DEBUG_FOCUS) {
5473 ALOGD("Trivial transfer to same window.");
5474 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005475 return true;
5476 }
5477
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005479 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480
Arthur Hungabbb9d82021-09-01 14:52:30 +00005481 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005482 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005483
Arthur Hungabbb9d82021-09-01 14:52:30 +00005484 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005485 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 return false;
5487 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005488 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5489 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005490 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5491 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005492 return false;
5493 }
5494 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005495
Arthur Hungabbb9d82021-09-01 14:52:30 +00005496 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5497 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005498 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005499 return false;
5500 }
5501
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005502 if (DEBUG_FOCUS) {
5503 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005504 touchedWindow->windowHandle->getName().c_str(),
5505 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 }
5507
Arthur Hungabbb9d82021-09-01 14:52:30 +00005508 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005509 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005510 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005511 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005512 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513
Arthur Hungabbb9d82021-09-01 14:52:30 +00005514 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005515 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005516 ftl::Flags<InputTarget::Flags> newTargetFlags =
5517 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005518 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005519 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005520 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005521 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5522 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523
Arthur Hungabbb9d82021-09-01 14:52:30 +00005524 // Store the dragging window.
5525 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005526 if (pointerIds.count() != 1) {
5527 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5528 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005529 return false;
5530 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005531 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005532 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005533 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 }
5535
Arthur Hungabbb9d82021-09-01 14:52:30 +00005536 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005537 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5538 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005539 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005540 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005541 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5542 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005544 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5545 newTargetFlags);
5546
5547 // Check if the wallpaper window should deliver the corresponding event.
5548 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005549 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 } // release lock
5552
5553 // Wake up poll loop since it may need to make new input dispatching choices.
5554 mLooper->wake();
5555 return true;
5556}
5557
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005558/**
5559 * Get the touched foreground window on the given display.
5560 * Return null if there are no windows touched on that display, or if more than one foreground
5561 * window is being touched.
5562 */
5563sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5564 auto stateIt = mTouchStatesByDisplay.find(displayId);
5565 if (stateIt == mTouchStatesByDisplay.end()) {
5566 ALOGI("No touch state on display %" PRId32, displayId);
5567 return nullptr;
5568 }
5569
5570 const TouchState& state = stateIt->second;
5571 sp<WindowInfoHandle> touchedForegroundWindow;
5572 // If multiple foreground windows are touched, return nullptr
5573 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005574 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005575 if (touchedForegroundWindow != nullptr) {
5576 ALOGI("Two or more foreground windows: %s and %s",
5577 touchedForegroundWindow->getName().c_str(),
5578 window.windowHandle->getName().c_str());
5579 return nullptr;
5580 }
5581 touchedForegroundWindow = window.windowHandle;
5582 }
5583 }
5584 return touchedForegroundWindow;
5585}
5586
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005587// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005588bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005589 sp<IBinder> fromToken;
5590 { // acquire lock
5591 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005592 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005593 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005594 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5595 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005596 return false;
5597 }
5598
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005599 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5600 if (from == nullptr) {
5601 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5602 return false;
5603 }
5604
5605 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005606 } // release lock
5607
5608 return transferTouchFocus(fromToken, destChannelToken);
5609}
5610
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005612 if (DEBUG_FOCUS) {
5613 ALOGD("Resetting and dropping all events (%s).", reason);
5614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615
Michael Wrightfb04fd52022-11-24 22:31:11 +00005616 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 synthesizeCancelationEventsForAllConnectionsLocked(options);
5618
5619 resetKeyRepeatLocked();
5620 releasePendingEventLocked();
5621 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005622 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005624 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005625 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626}
5627
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005628void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005629 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 dumpDispatchStateLocked(dump);
5631
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005632 std::istringstream stream(dump);
5633 std::string line;
5634
5635 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005636 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 }
5638}
5639
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005640std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005641 std::string dump;
5642
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005643 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5644 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005645
5646 std::string windowName = "None";
5647 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005648 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005649 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5650 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5651 : "token has capture without window";
5652 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005653 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005654
5655 return dump;
5656}
5657
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005658void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005659 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5660 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5661 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005662 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663
Tiger Huang721e26f2018-07-24 22:26:19 +08005664 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5665 dump += StringPrintf(INDENT "FocusedApplications:\n");
5666 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5667 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005668 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005669 const std::chrono::duration timeout =
5670 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005671 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005672 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005673 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005676 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005678
Vishnu Nairc519ff72021-01-21 08:23:08 -08005679 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005680 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005682 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005684 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005685 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5686 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 }
5688 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005689 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 }
5691
arthurhung6d4bed92021-03-17 11:59:33 +08005692 if (mDragState) {
5693 dump += StringPrintf(INDENT "DragState:\n");
5694 mDragState->dump(dump, INDENT2);
5695 }
5696
Arthur Hungb92218b2018-08-14 12:00:21 +08005697 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005698 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5699 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5700 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5701 const auto& displayInfo = it->second;
5702 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5703 displayInfo.logicalHeight);
5704 displayInfo.transform.dump(dump, "transform", INDENT4);
5705 } else {
5706 dump += INDENT2 "No DisplayInfo found!\n";
5707 }
5708
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005709 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005710 dump += INDENT2 "Windows:\n";
5711 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005712 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5713 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005715 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005716 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005717 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005718 "applicationInfo.name=%s, "
5719 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005720 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005721 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005722 windowInfo->displayId,
5723 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005724 windowInfo->alpha, windowInfo->frame.left,
5725 windowInfo->frame.top, windowInfo->frame.right,
5726 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005727 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005728 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005729 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005730 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005731 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005732 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005733 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005734 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005735 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005736 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005737 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005738 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005739 }
5740 } else {
5741 dump += INDENT2 "Windows: <none>\n";
5742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743 }
5744 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005745 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746 }
5747
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005748 if (!mGlobalMonitorsByDisplay.empty()) {
5749 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5750 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005751 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005754 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755 }
5756
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005757 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758
5759 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005760 if (!mRecentQueue.empty()) {
5761 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005762 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005763 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005764 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005765 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
5767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005768 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770
5771 // Dump event currently being dispatched.
5772 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005773 dump += INDENT "PendingEvent:\n";
5774 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005775 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005776 dump += StringPrintf(", age=%" PRId64 "ms\n",
5777 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005779 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781
5782 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005783 if (!mInboundQueue.empty()) {
5784 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005785 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005787 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005788 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 }
5790 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005791 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793
Prabir Pradhancef936d2021-07-21 16:17:52 +00005794 if (!mCommandQueue.empty()) {
5795 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5796 } else {
5797 dump += INDENT "CommandQueue: <empty>\n";
5798 }
5799
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005800 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005801 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005802 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005803 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005804 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005805 connection->inputChannel->getFd().get(),
5806 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005807 connection->getWindowName().c_str(),
5808 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005809 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005811 if (!connection->outboundQueue.empty()) {
5812 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5813 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005814 dump += dumpQueue(connection->outboundQueue, currentTime);
5815
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005817 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818 }
5819
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005820 if (!connection->waitQueue.empty()) {
5821 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5822 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005823 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005824 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005825 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005827 std::stringstream inputStateDump;
5828 inputStateDump << connection->inputState;
5829 if (!isEmpty(inputStateDump)) {
5830 dump += INDENT3 "InputState: ";
5831 dump += inputStateDump.str() + "\n";
5832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 }
5834 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005835 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836 }
5837
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005838 dump += "input_flags::remove_app_switch_drops() = ";
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07005839 dump += toString(REMOVE_APP_SWITCH_DROPS);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005840 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005842 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5843 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005845 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 }
5847
Antonio Kantek15beb512022-06-13 22:35:41 +00005848 if (!mTouchModePerDisplay.empty()) {
5849 dump += INDENT "TouchModePerDisplay:\n";
5850 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5851 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5852 std::to_string(touchMode).c_str());
5853 }
5854 } else {
5855 dump += INDENT "TouchModePerDisplay: <none>\n";
5856 }
5857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005858 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005859 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5860 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5861 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005862 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005863 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864}
5865
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005866void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005867 const size_t numMonitors = monitors.size();
5868 for (size_t i = 0; i < numMonitors; i++) {
5869 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005870 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005871 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5872 dump += "\n";
5873 }
5874}
5875
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005876class LooperEventCallback : public LooperCallback {
5877public:
5878 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5879 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5880
5881private:
5882 std::function<int(int events)> mCallback;
5883};
5884
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005885Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005886 if (DEBUG_CHANNEL_CREATION) {
5887 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005890 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005891 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005892 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005893
5894 if (result) {
5895 return base::Error(result) << "Failed to open input channel pair with name " << name;
5896 }
5897
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005899 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005900 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005901 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005902 std::shared_ptr<Connection> connection =
5903 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5904 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005906 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5907 ALOGE("Created a new connection, but the token %p is already known", token.get());
5908 }
5909 mConnectionsByToken.emplace(token, connection);
5910
5911 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5912 this, std::placeholders::_1, token);
5913
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005914 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5915 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916 } // release lock
5917
5918 // Wake the looper because some connections have changed.
5919 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005920 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921}
5922
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005923Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005924 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005925 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005926 std::shared_ptr<InputChannel> serverChannel;
5927 std::unique_ptr<InputChannel> clientChannel;
5928 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5929 if (result) {
5930 return base::Error(result) << "Failed to open input channel pair with name " << name;
5931 }
5932
Michael Wright3dd60e22019-03-27 22:06:44 +00005933 { // acquire lock
5934 std::scoped_lock _l(mLock);
5935
5936 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005937 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5938 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005939 }
5940
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005941 std::shared_ptr<Connection> connection =
5942 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005943 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005944 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005945
5946 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5947 ALOGE("Created a new connection, but the token %p is already known", token.get());
5948 }
5949 mConnectionsByToken.emplace(token, connection);
5950 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5951 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005952
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005953 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005954
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005955 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5956 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005957 }
Garfield Tan15601662020-09-22 15:32:38 -07005958
Michael Wright3dd60e22019-03-27 22:06:44 +00005959 // Wake the looper because some connections have changed.
5960 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005961 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005962}
5963
Garfield Tan15601662020-09-22 15:32:38 -07005964status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005966 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967
Harry Cutts33476232023-01-30 19:57:29 +00005968 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969 if (status) {
5970 return status;
5971 }
5972 } // release lock
5973
5974 // Wake the poll loop because removing the connection may have changed the current
5975 // synchronization state.
5976 mLooper->wake();
5977 return OK;
5978}
5979
Garfield Tan15601662020-09-22 15:32:38 -07005980status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5981 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005982 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005983 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005984 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005985 return BAD_VALUE;
5986 }
5987
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005988 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005989
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005991 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992 }
5993
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005994 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995
5996 nsecs_t currentTime = now();
5997 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5998
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005999 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000 return OK;
6001}
6002
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006003void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006004 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6005 auto& [displayId, monitors] = *it;
6006 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6007 return monitor.inputChannel->getConnectionToken() == connectionToken;
6008 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006009
Michael Wright3dd60e22019-03-27 22:06:44 +00006010 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006012 } else {
6013 ++it;
6014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 }
6016}
6017
Michael Wright3dd60e22019-03-27 22:06:44 +00006018status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006019 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006020 return pilferPointersLocked(token);
6021}
Michael Wright3dd60e22019-03-27 22:06:44 +00006022
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006023status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006024 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6025 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006026 LOG(WARNING)
6027 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006028 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006029 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006030
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006031 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006032 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006033 LOG(WARNING)
6034 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6035 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006036 return BAD_VALUE;
6037 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006038 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006039 if (deviceIds.empty()) {
6040 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006041 return BAD_VALUE;
6042 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006043
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006044 for (const DeviceId deviceId : deviceIds) {
6045 TouchState& state = *statePtr;
6046 TouchedWindow& window = *windowPtr;
6047 // Send cancel events to all the input channels we're stealing from.
6048 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6049 "input channel stole pointer stream");
6050 options.deviceId = deviceId;
6051 options.displayId = displayId;
6052 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6053 options.pointerIds = pointerIds;
6054 std::string canceledWindows;
6055 for (const TouchedWindow& w : state.windows) {
6056 const std::shared_ptr<InputChannel> channel =
6057 getInputChannelLocked(w.windowHandle->getToken());
6058 if (channel != nullptr && channel->getConnectionToken() != token) {
6059 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6060 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6061 canceledWindows += channel->getName();
6062 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006063 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006064 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6065 LOG(INFO) << "Channel " << requestingChannel->getName()
6066 << " is stealing input gesture for device " << deviceId << " from "
6067 << canceledWindows;
6068
6069 // Prevent the gesture from being sent to any other windows.
6070 // This only blocks relevant pointers to be sent to other windows
6071 window.addPilferingPointers(deviceId, pointerIds);
6072
6073 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006075 return OK;
6076}
6077
Prabir Pradhan99987712020-11-10 18:43:05 -08006078void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6079 { // acquire lock
6080 std::scoped_lock _l(mLock);
6081 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006082 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006083 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6084 windowHandle != nullptr ? windowHandle->getName().c_str()
6085 : "token without window");
6086 }
6087
Vishnu Nairc519ff72021-01-21 08:23:08 -08006088 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006089 if (focusedToken != windowToken) {
6090 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6091 enabled ? "enable" : "disable");
6092 return;
6093 }
6094
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006095 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006096 ALOGW("Ignoring request to %s Pointer Capture: "
6097 "window has %s requested pointer capture.",
6098 enabled ? "enable" : "disable", enabled ? "already" : "not");
6099 return;
6100 }
6101
Christine Franksb768bb42021-11-29 12:11:31 -08006102 if (enabled) {
6103 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6104 mIneligibleDisplaysForPointerCapture.end(),
6105 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6106 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6107 return;
6108 }
6109 }
6110
Prabir Pradhan99987712020-11-10 18:43:05 -08006111 setPointerCaptureLocked(enabled);
6112 } // release lock
6113
6114 // Wake the thread to process command entries.
6115 mLooper->wake();
6116}
6117
Christine Franksb768bb42021-11-29 12:11:31 -08006118void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6119 { // acquire lock
6120 std::scoped_lock _l(mLock);
6121 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6122 if (!isEligible) {
6123 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6124 }
6125 } // release lock
6126}
6127
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006128std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006129 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006130 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006131 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006132 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006133 }
6134 }
6135 }
6136 return std::nullopt;
6137}
6138
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006139std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6140 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006141 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006142 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006143 }
6144
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006145 for (const auto& [token, connection] : mConnectionsByToken) {
6146 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006147 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148 }
6149 }
Robert Carr4e670e52018-08-15 13:26:12 -07006150
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006151 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006152}
6153
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006154std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006155 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006156 if (connection == nullptr) {
6157 return "<nullptr>";
6158 }
6159 return connection->getInputChannelName();
6160}
6161
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006162void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006163 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006164 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006165}
6166
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006168 const std::shared_ptr<Connection>& connection,
6169 uint32_t seq, bool handled,
6170 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171 // Handle post-event policy actions.
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006172 std::unique_ptr<KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006173
6174 { // Start critical section
6175 auto dispatchEntryIt =
6176 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6177 [seq](auto& e) { return e->seq == seq; });
6178 if (dispatchEntryIt == connection->waitQueue.end()) {
6179 return;
6180 }
6181
6182 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6183
6184 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6185 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6186 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6187 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6188 }
6189 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6190 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6191 connection->inputChannel->getConnectionToken(),
6192 dispatchEntry.deliveryTime, consumeTime, finishTime);
6193 }
6194
6195 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006196 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6197 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006198 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006199 }
6200 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006201
6202 // Dequeue the event and start the next cycle.
6203 // Because the lock might have been released, it is possible that the
6204 // contents of the wait queue to have been drained, so we need to double-check
6205 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006206 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6207 [seq](auto& e) { return e->seq == seq; });
6208 if (entryIt != connection->waitQueue.end()) {
6209 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6210 connection->waitQueue.erase(entryIt);
6211
Prabir Pradhancef936d2021-07-21 16:17:52 +00006212 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6213 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6214 if (!connection->responsive) {
6215 connection->responsive = isConnectionResponsive(*connection);
6216 if (connection->responsive) {
6217 // The connection was unresponsive, and now it's responsive.
6218 processConnectionResponsiveLocked(*connection);
6219 }
6220 }
6221 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006222 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6223 const InputTarget target{.inputChannel = connection->inputChannel,
6224 .flags = dispatchEntry->targetFlags};
6225 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target,
6226 InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006227 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006228 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229 }
6230
6231 // Start the next dispatch cycle for this connection.
6232 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233}
6234
Prabir Pradhancef936d2021-07-21 16:17:52 +00006235void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6236 const sp<IBinder>& newToken) {
6237 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6238 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006239 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006240 };
6241 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242}
6243
Prabir Pradhancef936d2021-07-21 16:17:52 +00006244void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6245 auto command = [this, token, x, y]() REQUIRES(mLock) {
6246 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006247 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006248 };
6249 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006250}
6251
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006252void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006253 if (connection == nullptr) {
6254 LOG_ALWAYS_FATAL("Caller must check for nullness");
6255 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006256 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6257 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006258 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006259 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006260 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006261 return;
6262 }
6263 /**
6264 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6265 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6266 * has changed. This could cause newer entries to time out before the already dispatched
6267 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6268 * processes the events linearly. So providing information about the oldest entry seems to be
6269 * most useful.
6270 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006271 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6272 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006273 std::string reason =
6274 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006275 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006276 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006277 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006278 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006279 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006280
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006281 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6282
6283 // Stop waking up for events on this connection, it is already unresponsive
6284 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006285}
6286
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006287void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6288 std::string reason =
6289 StringPrintf("%s does not have a focused window", application->getName().c_str());
6290 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006291
Yabin Cui8eb9c552023-06-08 18:05:07 +00006292 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006294 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006295 };
6296 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006297}
6298
chaviw98318de2021-05-19 16:45:23 -05006299void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006300 const std::string& reason) {
6301 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6302 updateLastAnrStateLocked(windowLabel, reason);
6303}
6304
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006305void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6306 const std::string& reason) {
6307 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006308 updateLastAnrStateLocked(windowLabel, reason);
6309}
6310
6311void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6312 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006314 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006315 struct tm tm;
6316 localtime_r(&t, &tm);
6317 char timestr[64];
6318 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006319 mLastAnrState.clear();
6320 mLastAnrState += INDENT "ANR:\n";
6321 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006322 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6323 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006324 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006325}
6326
Prabir Pradhancef936d2021-07-21 16:17:52 +00006327void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6328 KeyEntry& entry) {
6329 const KeyEvent event = createKeyEvent(entry);
6330 nsecs_t delay = 0;
6331 { // release lock
6332 scoped_unlock unlock(mLock);
6333 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006334 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006335 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6336 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6337 std::to_string(t.duration().count()).c_str());
6338 }
6339 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006340
6341 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006342 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006343 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006344 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006346 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006347 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349}
6350
Prabir Pradhancef936d2021-07-21 16:17:52 +00006351void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006352 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006353 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006354 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006355 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006356 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006357 };
6358 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006359}
6360
Prabir Pradhanedd96402022-02-15 01:46:16 -08006361void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006362 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006363 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006364 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006365 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006366 };
6367 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006368}
6369
6370/**
6371 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6372 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6373 * command entry to the command queue.
6374 */
6375void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6376 std::string reason) {
6377 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006378 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006379 if (connection.monitor) {
6380 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6381 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006382 pid = findMonitorPidByTokenLocked(connectionToken);
6383 } else {
6384 // The connection is a window
6385 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6386 reason.c_str());
6387 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6388 if (handle != nullptr) {
6389 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006390 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006391 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006392 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006393}
6394
6395/**
6396 * Tell the policy that a connection has become responsive so that it can stop ANR.
6397 */
6398void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6399 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006400 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006401 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006402 pid = findMonitorPidByTokenLocked(connectionToken);
6403 } else {
6404 // The connection is a window
6405 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6406 if (handle != nullptr) {
6407 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006408 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006409 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006410 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006411}
6412
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006413std::unique_ptr<KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006414 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006415 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006416 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006417 if (!handled) {
6418 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006419 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006420 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006421 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006424 // Get the fallback key state.
6425 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006426 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006427 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006428 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006429 connection->inputState.removeFallbackKey(originalKeyCode);
6430 }
6431
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006432 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006433 // If the application handles the original key for which we previously
6434 // generated a fallback or if the window is not a foreground window,
6435 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006436 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006437 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006438 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6439 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6440 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6441 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6442 keyEntry.policyFlags);
6443 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006444 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006445 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446
6447 mLock.unlock();
6448
Prabir Pradhana41d2442023-04-20 21:30:40 +00006449 if (const auto unhandledKeyFallback =
6450 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6451 event, keyEntry.policyFlags);
6452 unhandledKeyFallback) {
6453 event = *unhandledKeyFallback;
6454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006455
6456 mLock.lock();
6457
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006458 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006459 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006460 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 "application handled the original non-fallback key "
6462 "or is no longer a foreground target, "
6463 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006464 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006465 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006466 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006467 connection->inputState.removeFallbackKey(originalKeyCode);
6468 }
6469 } else {
6470 // If the application did not handle a non-fallback key, first check
6471 // that we are in a good state to perform unhandled key event processing
6472 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006473 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006474 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006475 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6476 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6477 "since this is not an initial down. "
6478 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6479 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6480 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006481 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006484 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006485 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6486 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6487 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6488 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6489 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006490 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491
6492 mLock.unlock();
6493
Prabir Pradhana41d2442023-04-20 21:30:40 +00006494 bool fallback = false;
6495 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6496 event, keyEntry.policyFlags);
6497 fb) {
6498 fallback = true;
6499 event = *fb;
6500 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501
6502 mLock.lock();
6503
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006504 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006505 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006506 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006507 }
6508
6509 // Latch the fallback keycode for this key on an initial down.
6510 // The fallback keycode cannot change at any other point in the lifecycle.
6511 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006513 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006514 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006515 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006516 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006517 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006518 }
6519
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006520 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006521
6522 // Cancel the fallback key if the policy decides not to send it anymore.
6523 // We will continue to dispatch the key to the policy but we will no
6524 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006525 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6526 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6528 if (fallback) {
6529 ALOGD("Unhandled key event: Policy requested to send key %d"
6530 "as a fallback for %d, but on the DOWN it had requested "
6531 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006533 } else {
6534 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6535 "but on the DOWN it had requested to send %d. "
6536 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006537 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006538 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006539 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006540
Michael Wrightfb04fd52022-11-24 22:31:11 +00006541 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006542 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006543 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006544 synthesizeCancelationEventsForConnectionLocked(connection, options);
6545
6546 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006547 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006548 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006549 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006550 }
6551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006553 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6554 {
6555 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006556 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006557 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006558 for (const auto& [key, value] : fallbackKeys) {
6559 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006560 }
6561 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6562 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006563 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006564 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006565
6566 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006567 // Return the fallback key that we want dispatched to the channel.
6568 std::unique_ptr<KeyEntry> newEntry =
6569 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6570 event.getEventTime(), event.getDeviceId(),
6571 event.getSource(), event.getDisplayId(),
6572 keyEntry.policyFlags, keyEntry.action,
6573 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6574 *fallbackKeyCode, event.getScanCode(),
6575 event.getMetaState(), event.getRepeatCount(),
6576 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006577 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6578 ALOGD("Unhandled key event: Dispatching fallback key. "
6579 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006580 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006581 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006582 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006584 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6585 ALOGD("Unhandled key event: No fallback key.");
6586 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006587
6588 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006589 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590 }
6591 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006592 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593}
6594
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595void InputDispatcher::traceInboundQueueLengthLocked() {
6596 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006597 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598 }
6599}
6600
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006601void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006602 if (ATRACE_ENABLED()) {
6603 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006604 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6605 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006606 }
6607}
6608
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006609void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610 if (ATRACE_ENABLED()) {
6611 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006612 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6613 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006614 }
6615}
6616
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006617void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006618 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006620 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006621 dumpDispatchStateLocked(dump);
6622
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006623 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006624 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006625 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006626 }
6627}
6628
6629void InputDispatcher::monitor() {
6630 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006631 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006633 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006634}
6635
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006636/**
6637 * Wake up the dispatcher and wait until it processes all events and commands.
6638 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6639 * this method can be safely called from any thread, as long as you've ensured that
6640 * the work you are interested in completing has already been queued.
6641 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006642bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006643 /**
6644 * Timeout should represent the longest possible time that a device might spend processing
6645 * events and commands.
6646 */
6647 constexpr std::chrono::duration TIMEOUT = 100ms;
6648 std::unique_lock lock(mLock);
6649 mLooper->wake();
6650 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6651 return result == std::cv_status::no_timeout;
6652}
6653
Vishnu Naire798b472020-07-23 13:52:21 -07006654/**
6655 * Sets focus to the window identified by the token. This must be called
6656 * after updating any input window handles.
6657 *
6658 * Params:
6659 * request.token - input channel token used to identify the window that should gain focus.
6660 * request.focusedToken - the token that the caller expects currently to be focused. If the
6661 * specified token does not match the currently focused window, this request will be dropped.
6662 * If the specified focused token matches the currently focused window, the call will succeed.
6663 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6664 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6665 * when requesting the focus change. This determines which request gets
6666 * precedence if there is a focus change request from another source such as pointer down.
6667 */
Vishnu Nair958da932020-08-21 17:12:37 -07006668void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6669 { // acquire lock
6670 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006671 std::optional<FocusResolver::FocusChanges> changes =
6672 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6673 if (changes) {
6674 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006675 }
6676 } // release lock
6677 // Wake up poll loop since it may need to make new input dispatching choices.
6678 mLooper->wake();
6679}
6680
Vishnu Nairc519ff72021-01-21 08:23:08 -08006681void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6682 if (changes.oldFocus) {
6683 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006684 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006685 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006686 "focus left window");
6687 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006688 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006689 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006690 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006691 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006692 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006693 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006694 }
6695
Prabir Pradhan99987712020-11-10 18:43:05 -08006696 // If a window has pointer capture, then it must have focus. We need to ensure that this
6697 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6698 // If the window loses focus before it loses pointer capture, then the window can be in a state
6699 // where it has pointer capture but not focus, violating the contract. Therefore we must
6700 // dispatch the pointer capture event before the focus event. Since focus events are added to
6701 // the front of the queue (above), we add the pointer capture event to the front of the queue
6702 // after the focus events are added. This ensures the pointer capture event ends up at the
6703 // front.
6704 disablePointerCaptureForcedLocked();
6705
Vishnu Nairc519ff72021-01-21 08:23:08 -08006706 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006707 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006708 }
6709}
Vishnu Nair958da932020-08-21 17:12:37 -07006710
Prabir Pradhan99987712020-11-10 18:43:05 -08006711void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006712 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006713 return;
6714 }
6715
6716 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6717
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006718 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006719 setPointerCaptureLocked(false);
6720 }
6721
6722 if (!mWindowTokenWithPointerCapture) {
6723 // No need to send capture changes because no window has capture.
6724 return;
6725 }
6726
6727 if (mPendingEvent != nullptr) {
6728 // Move the pending event to the front of the queue. This will give the chance
6729 // for the pending event to be dropped if it is a captured event.
6730 mInboundQueue.push_front(mPendingEvent);
6731 mPendingEvent = nullptr;
6732 }
6733
6734 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006735 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006736 mInboundQueue.push_front(std::move(entry));
6737}
6738
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006739void InputDispatcher::setPointerCaptureLocked(bool enable) {
6740 mCurrentPointerCaptureRequest.enable = enable;
6741 mCurrentPointerCaptureRequest.seq++;
6742 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006743 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006744 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006745 };
6746 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006747}
6748
Vishnu Nair599f1412021-06-21 10:39:58 -07006749void InputDispatcher::displayRemoved(int32_t displayId) {
6750 { // acquire lock
6751 std::scoped_lock _l(mLock);
6752 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006753 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006754 setFocusedApplicationLocked(displayId, nullptr);
6755 // Call focus resolver to clean up stale requests. This must be called after input windows
6756 // have been removed for the removed display.
6757 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006758 // Reset pointer capture eligibility, regardless of previous state.
6759 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006760 // Remove the associated touch mode state.
6761 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006762 mVerifiersByDisplay.erase(displayId);
Siarhei Vishniakou96e4fad2023-09-20 09:30:44 -07006763 mInputFilterVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006764 } // release lock
6765
6766 // Wake up poll loop since it may need to make new input dispatching choices.
6767 mLooper->wake();
6768}
6769
Patrick Williamsd828f302023-04-28 17:52:08 -05006770void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006771 // The listener sends the windows as a flattened array. Separate the windows by display for
6772 // more convenient parsing.
6773 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006774 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006775 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006776 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006777 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006778
6779 { // acquire lock
6780 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006781
6782 // Ensure that we have an entry created for all existing displays so that if a displayId has
6783 // no windows, we can tell that the windows were removed from the display.
6784 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6785 handlesPerDisplay[displayId];
6786 }
6787
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006788 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006789 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006790 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6791 }
6792
6793 for (const auto& [displayId, handles] : handlesPerDisplay) {
6794 setInputWindowsLocked(handles, displayId);
6795 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006796
6797 if (update.vsyncId < mWindowInfosVsyncId) {
6798 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6799 ", current update vsync id: %" PRId64,
6800 mWindowInfosVsyncId, update.vsyncId);
6801 }
6802 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006803 }
6804 // Wake up poll loop since it may need to make new input dispatching choices.
6805 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006806}
6807
Vishnu Nair062a8672021-09-03 16:07:44 -07006808bool InputDispatcher::shouldDropInput(
6809 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006810 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6811 (windowHandle->getInfo()->inputConfig.test(
6812 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006813 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006814 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6815 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006816 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006817 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006818 windowHandle->getInfo()->displayId);
6819 return true;
6820 }
6821 return false;
6822}
6823
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006824void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006825 const gui::WindowInfosUpdate& update) {
6826 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006827}
6828
Arthur Hungdfd528e2021-12-08 13:23:04 +00006829void InputDispatcher::cancelCurrentTouch() {
6830 {
6831 std::scoped_lock _l(mLock);
6832 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006833 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006834 "cancel current touch");
6835 synthesizeCancelationEventsForAllConnectionsLocked(options);
6836
6837 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006838 }
6839 // Wake up poll loop since there might be work to do.
6840 mLooper->wake();
6841}
6842
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006843void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6844 std::scoped_lock _l(mLock);
6845 mMonitorDispatchingTimeout = timeout;
6846}
6847
Arthur Hungc539dbb2022-12-08 07:45:36 +00006848void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6849 const sp<WindowInfoHandle>& oldWindowHandle,
6850 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006851 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006852 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006853 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6854 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006855 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6856 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6857 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6858 newWindowHandle->getInfo()->inputConfig.test(
6859 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6860 const sp<WindowInfoHandle> oldWallpaper =
6861 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6862 const sp<WindowInfoHandle> newWallpaper =
6863 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6864 if (oldWallpaper == newWallpaper) {
6865 return;
6866 }
6867
6868 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006869 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006870 addPointerWindowTargetLocked(oldWallpaper,
6871 oldTouchedWindow.targetFlags |
6872 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6873 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId),
6874 targets);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006875 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006876 }
6877
6878 if (newWallpaper != nullptr) {
6879 state.addOrUpdateWindow(newWallpaper,
6880 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6881 InputTarget::Flags::WINDOW_IS_OBSCURED |
6882 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006883 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006884 }
6885}
6886
6887void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6888 ftl::Flags<InputTarget::Flags> newTargetFlags,
6889 const sp<WindowInfoHandle> fromWindowHandle,
6890 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006891 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006892 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006893 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6894 fromWindowHandle->getInfo()->inputConfig.test(
6895 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6896 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6897 toWindowHandle->getInfo()->inputConfig.test(
6898 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6899
6900 const sp<WindowInfoHandle> oldWallpaper =
6901 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6902 const sp<WindowInfoHandle> newWallpaper =
6903 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6904 if (oldWallpaper == newWallpaper) {
6905 return;
6906 }
6907
6908 if (oldWallpaper != nullptr) {
6909 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6910 "transferring touch focus to another window");
6911 state.removeWindowByToken(oldWallpaper->getToken());
6912 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6913 }
6914
6915 if (newWallpaper != nullptr) {
6916 nsecs_t downTimeInTarget = now();
6917 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6918 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6919 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6920 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006921 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6922 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006923 std::shared_ptr<Connection> wallpaperConnection =
6924 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006925 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006926 std::shared_ptr<Connection> toConnection =
6927 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006928 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6929 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6930 wallpaperFlags);
6931 }
6932 }
6933}
6934
6935sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6936 const sp<WindowInfoHandle>& windowHandle) const {
6937 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6938 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6939 bool foundWindow = false;
6940 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6941 if (!foundWindow && otherHandle != windowHandle) {
6942 continue;
6943 }
6944 if (windowHandle == otherHandle) {
6945 foundWindow = true;
6946 continue;
6947 }
6948
6949 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6950 return otherHandle;
6951 }
6952 }
6953 return nullptr;
6954}
6955
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006956void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6957 std::scoped_lock _l(mLock);
6958
6959 mConfig.keyRepeatTimeout = timeout;
6960 mConfig.keyRepeatDelay = delay;
6961}
6962
Garfield Tane84e6f92019-08-29 17:28:41 -07006963} // namespace android::inputdispatcher