blob: d356549e769a52c05d711d15583c55159f666804 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056#define INDENT " "
57#define INDENT2 " "
58#define INDENT3 " "
59#define INDENT4 " "
60
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080061using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070062using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080063using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000064using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070066using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050067using android::gui::FocusRequest;
68using android::gui::TouchOcclusionMode;
69using android::gui::WindowInfo;
70using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080071using android::os::InputEventInjectionResult;
72using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000073namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080074
Siarhei Vishniakou18a1d512023-12-15 13:47:33 -080075// TODO(b/312714754): remove the corresponding code, as well.
76static const bool REMOVE_APP_SWITCH_DROPS = true;
Siarhei Vishniakou17f12282023-11-02 13:40:29 -070077
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
Prabir Pradhancef936d2021-07-21 16:17:52 +000080namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000081// Temporarily releases a held mutex for the lifetime of the instance.
82// Named to match std::scoped_lock
83class scoped_unlock {
84public:
85 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
86 ~scoped_unlock() { mMutex.lock(); }
87
88private:
89 std::mutex& mMutex;
90};
91
Michael Wrightd02c5b62014-02-10 15:10:22 -080092// Default input dispatching timeout if there is no focused application or paused window
93// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080094const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
95 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
96 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Amount of time to allow for all pending events to be processed when an app switch
99// key is on the way. This is used to preempt input dispatch and drop input events
100// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000101constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800103const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// 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 +0000106constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
107
108// Log a warning when an interception call takes longer than this to process.
109constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700111// Additional key latency in case a connection is still processing some motion events.
112// This will help with the case when a user touched a button that opens a new window,
113// and gives us the chance to dispatch the key to this new window.
114constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
115
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000117constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
118
Antonio Kantekea47acb2021-12-23 12:41:25 -0800119// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000120constexpr int LOGTAG_INPUT_INTERACTION = 62000;
121constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000122constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000123
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000124const ui::Transform kIdentityTransform;
125
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000126inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 return systemTime(SYSTEM_TIME_MONOTONIC);
128}
129
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700130inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000131 if (binder == nullptr) {
132 return "<null>";
133 }
134 return StringPrintf("%p", binder.get());
135}
136
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000137static std::string uidString(const gui::Uid& uid) {
138 return uid.toString();
139}
140
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700141Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 case AKEY_EVENT_ACTION_DOWN:
144 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700145 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700147 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 }
149}
150
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700151Result<void> validateKeyEvent(int32_t action) {
152 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153}
154
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800156 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700158 case AMOTION_EVENT_ACTION_UP: {
159 if (pointerCount != 1) {
160 return Error() << "invalid pointer count " << pointerCount;
161 }
162 return {};
163 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_HOVER_ENTER:
166 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700167 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
168 if (pointerCount < 1) {
169 return Error() << "invalid pointer count " << pointerCount;
170 }
171 return {};
172 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800173 case AMOTION_EVENT_ACTION_CANCEL:
174 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700176 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 case AMOTION_EVENT_ACTION_POINTER_DOWN:
178 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800179 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700180 if (index < 0) {
181 return Error() << "invalid index " << index << " for "
182 << MotionEvent::actionToString(action);
183 }
184 if (index >= pointerCount) {
185 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
186 }
187 if (pointerCount <= 1) {
188 return Error() << "invalid pointer count " << pointerCount << " for "
189 << MotionEvent::actionToString(action);
190 }
191 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700192 }
193 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700194 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
195 if (actionButton == 0) {
196 return Error() << "action button should be nonzero for "
197 << MotionEvent::actionToString(action);
198 }
199 return {};
200 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700201 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700202 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 }
204}
205
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000206int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500207 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
208}
209
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700210Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
211 const PointerProperties* pointerProperties) {
212 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
213 if (!actionCheck.ok()) {
214 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 }
216 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700217 return Error() << "Motion event has invalid pointer count " << pointerCount
218 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800220 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 for (size_t i = 0; i < pointerCount; i++) {
222 int32_t id = pointerProperties[i].id;
223 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700224 return Error() << "Motion event has invalid pointer id " << id
225 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700228 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800230 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 return {};
233}
234
235Result<void> validateInputEvent(const InputEvent& event) {
236 switch (event.getType()) {
237 case InputEventType::KEY: {
238 const KeyEvent& key = static_cast<const KeyEvent&>(event);
239 const int32_t action = key.getAction();
240 return validateKeyEvent(action);
241 }
242 case InputEventType::MOTION: {
243 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
244 const int32_t action = motion.getAction();
245 const size_t pointerCount = motion.getPointerCount();
246 const PointerProperties* pointerProperties = motion.getPointerProperties();
247 const int32_t actionButton = motion.getActionButton();
248 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
249 }
250 default: {
251 return {};
252 }
253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254}
255
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000256std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 }
260
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000261 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 bool first = true;
263 Region::const_iterator cur = region.begin();
264 Region::const_iterator const tail = region.end();
265 while (cur != tail) {
266 if (first) {
267 first = false;
268 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800269 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800271 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272 cur++;
273 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000274 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275}
276
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000277std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
278 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500279 constexpr size_t maxEntries = 50; // max events to print
280 constexpr size_t skipBegin = maxEntries / 2;
281 const size_t skipEnd = queue.size() - maxEntries / 2;
282 // skip from maxEntries / 2 ... size() - maxEntries/2
283 // only print from 0 .. skipBegin and then from skipEnd .. size()
284
285 std::string dump;
286 for (size_t i = 0; i < queue.size(); i++) {
287 const DispatchEntry& entry = *queue[i];
288 if (i >= skipBegin && i < skipEnd) {
289 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
290 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
291 continue;
292 }
293 dump.append(INDENT4);
294 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000295 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
296 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500297 ns2ms(currentTime - entry.eventEntry->eventTime));
298 if (entry.deliveryTime != 0) {
299 // This entry was delivered, so add information on how long we've been waiting
300 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
301 }
302 dump.append("\n");
303 }
304 return dump;
305}
306
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700307/**
308 * Find the entry in std::unordered_map by key, and return it.
309 * If the entry is not found, return a default constructed entry.
310 *
311 * Useful when the entries are vectors, since an empty vector will be returned
312 * if the entry is not found.
313 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
314 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000316V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700317 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700318 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800319}
320
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000321bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700322 if (first == second) {
323 return true;
324 }
325
326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329
330 return first->getToken() == second->getToken();
331}
332
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000333bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000334 if (first == nullptr || second == nullptr) {
335 return false;
336 }
337 return first->applicationInfo.token != nullptr &&
338 first->applicationInfo.token == second->applicationInfo.token;
339}
340
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800341template <typename T>
342size_t firstMarkedBit(T set) {
343 // TODO: replace with std::countr_zero from <bit> when that's available
344 LOG_ALWAYS_FATAL_IF(set.none());
345 size_t i = 0;
346 while (!set.test(i)) {
347 i++;
348 }
349 return i;
350}
351
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800352std::unique_ptr<DispatchEntry> createDispatchEntry(
Prabir Pradhan24047542023-11-02 17:14:59 +0000353 const InputTarget& inputTarget, std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800354 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 if (inputTarget.useDefaultPointerTransform()) {
356 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700358 inputTarget.displayTransform,
359 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360 }
361
362 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700365 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700366 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 // Use the first pointer information to normalize all other pointers. This could be any pointer
369 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // uses the transform for the normalized pointer.
371 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800372 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700373 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374
375 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700376 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000377 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
378 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 // First, apply the current pointer's transform to update the coordinates into
383 // window space.
384 pointerCoords[pointerIndex].transform(currTransform);
385 // Next, apply the inverse transform of the normalized coordinates so the
386 // current coordinates are transformed into the normalized coordinate space.
387 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388 }
389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700390 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000391 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
392 motionEntry.eventTime, motionEntry.deviceId,
393 motionEntry.source, motionEntry.displayId,
394 motionEntry.policyFlags, motionEntry.action,
395 motionEntry.actionButton, motionEntry.flags,
396 motionEntry.metaState, motionEntry.buttonState,
397 motionEntry.classification, motionEntry.edgeFlags,
398 motionEntry.xPrecision, motionEntry.yPrecision,
399 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
400 motionEntry.downTime, motionEntry.pointerProperties,
401 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000402
403 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700404 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700405 firstPointerTransform, inputTarget.displayTransform,
406 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000407 return dispatchEntry;
408}
409
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000410status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
411 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700412 std::unique_ptr<InputChannel> uniqueServerChannel;
413 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
414
415 serverChannel = std::move(uniqueServerChannel);
416 return result;
417}
418
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500419template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000420bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500421 if (lhs == nullptr && rhs == nullptr) {
422 return true;
423 }
424 if (lhs == nullptr || rhs == nullptr) {
425 return false;
426 }
427 return *lhs == *rhs;
428}
429
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000430KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000431 KeyEvent event;
432 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
433 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
434 entry.repeatCount, entry.downTime, entry.eventTime);
435 return event;
436}
437
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000438bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000439 // Do not keep track of gesture monitors. They receive every event and would disproportionately
440 // affect the statistics.
441 if (connection.monitor) {
442 return false;
443 }
444 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
445 if (!connection.responsive) {
446 return false;
447 }
448 return true;
449}
450
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000451bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000452 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
453 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
455 return false;
456 }
457 // Only track latency for events that originated from hardware
458 if (eventEntry.isSynthesized()) {
459 return false;
460 }
461 const EventEntry::Type& inputEventEntryType = eventEntry.type;
462 if (inputEventEntryType == EventEntry::Type::KEY) {
463 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
464 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
465 return false;
466 }
467 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
468 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
469 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
470 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
471 return false;
472 }
473 } else {
474 // Not a key or a motion
475 return false;
476 }
477 if (!shouldReportMetricsForConnection(connection)) {
478 return false;
479 }
480 return true;
481}
482
Prabir Pradhancef936d2021-07-21 16:17:52 +0000483/**
484 * Connection is responsive if it has no events in the waitQueue that are older than the
485 * current time.
486 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000487bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000488 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000489 for (const auto& dispatchEntry : connection.waitQueue) {
490 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000491 return false;
492 }
493 }
494 return true;
495}
496
Antonio Kantekf16f2832021-09-28 04:39:20 +0000497// Returns true if the event type passed as argument represents a user activity.
498bool isUserActivityEvent(const EventEntry& eventEntry) {
499 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000500 case EventEntry::Type::CONFIGURATION_CHANGED:
501 case EventEntry::Type::DEVICE_RESET:
502 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000503 case EventEntry::Type::FOCUS:
504 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000505 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000506 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000508 case EventEntry::Type::KEY:
509 case EventEntry::Type::MOTION:
510 return true;
511 }
512}
513
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800514// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000515bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000516 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800517 const auto inputConfig = windowInfo.inputConfig;
518 if (windowInfo.displayId != displayId ||
519 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800520 return false;
521 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700522 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800523 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524 return false;
525 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526
527 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
528 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
529 // the window. Points on the right and bottom edges should not be inside the window, so we need
530 // to be careful about performing a hit test when the display is rotated, since the "right" and
531 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
532 // logical display in which WM determined the bounds. Perform the hit test in the logical
533 // display space to ensure these edges are considered correctly in all orientations.
534 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
535 const auto p = displayTransform.transform(x, y);
536 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800537 return false;
538 }
539 return true;
540}
541
Prabir Pradhand65552b2021-10-07 11:23:50 -0700542bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
543 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000544 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700545}
546
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800547// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000548// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
549// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
550// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800551// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000552bool canReceiveForegroundTouches(const WindowInfo& info) {
553 // A non-touchable window can still receive touch events (e.g. in the case of
554 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
555 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
556}
557
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000558bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700559 if (windowHandle == nullptr) {
560 return false;
561 }
562 const WindowInfo* windowInfo = windowHandle->getInfo();
563 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
564 return true;
565 }
566 return false;
567}
568
Prabir Pradhan5735a322022-04-11 17:23:34 +0000569// Checks targeted injection using the window's owner's uid.
570// Returns an empty string if an entry can be sent to the given window, or an error message if the
571// entry is a targeted injection whose uid target doesn't match the window owner.
572std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
573 const EventEntry& entry) {
574 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
575 // The event was not injected, or the injected event does not target a window.
576 return {};
577 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000578 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000580 return StringPrintf("No valid window target for injection into uid %s.",
581 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000582 }
583 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000584 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
585 "owned by uid %s.",
586 uid.toString().c_str(), window->getName().c_str(),
587 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 }
589 return {};
590}
591
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000592std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700593 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
594 // Always dispatch mouse events to cursor position.
595 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000596 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700597 }
598
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700599 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000600 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
601 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602}
603
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700604std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
605 if (eventEntry.type == EventEntry::Type::KEY) {
606 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
607 return keyEntry.downTime;
608 } else if (eventEntry.type == EventEntry::Type::MOTION) {
609 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
610 return motionEntry.downTime;
611 }
612 return std::nullopt;
613}
614
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000615/**
616 * Compare the old touch state to the new touch state, and generate the corresponding touched
617 * windows (== input targets).
618 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
619 * If the pointer just entered the new window, produce HOVER_ENTER.
620 * For pointers remaining in the window, produce HOVER_MOVE.
621 */
622std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
623 const TouchState& newTouchState,
624 const MotionEntry& entry) {
625 std::vector<TouchedWindow> out;
626 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700627
628 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
629 // ACTION_SCROLL events should not affect the hovering pointer dispatch
630 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000631 }
632
633 // We should consider all hovering pointers here. But for now, just use the first one
634 const int32_t pointerId = entry.pointerProperties[0].id;
635
636 std::set<sp<WindowInfoHandle>> oldWindows;
637 if (oldState != nullptr) {
638 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
639 }
640
641 std::set<sp<WindowInfoHandle>> newWindows =
642 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
643
644 // If the pointer is no longer in the new window set, send HOVER_EXIT.
645 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
646 if (newWindows.find(oldWindow) == newWindows.end()) {
647 TouchedWindow touchedWindow;
648 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000649 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000650 out.push_back(touchedWindow);
651 }
652 }
653
654 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
655 TouchedWindow touchedWindow;
656 touchedWindow.windowHandle = newWindow;
657 if (oldWindows.find(newWindow) == oldWindows.end()) {
658 // Any windows that have this pointer now, and didn't have it before, should get
659 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000660 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000661 } else {
662 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700663 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700664 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000665 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
666 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700667 // The Accessibility injected touch exploration event stream
668 // has known inconsistencies, so log ERROR instead of
669 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700670 severity = android::base::LogSeverity::ERROR;
671 }
672 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000674 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000675 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700676 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
678 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
679 }
680 out.push_back(touchedWindow);
681 }
682 return out;
683}
684
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800685template <typename T>
686std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
687 left.insert(left.end(), right.begin(), right.end());
688 return left;
689}
690
Harry Cuttsb166c002023-05-09 13:06:05 +0000691// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
692// both.
693void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
694 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
695 if (!window.windowHandle->getInfo()->inputConfig.test(
696 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
697 // In addition to TouchState, erase this window from the input targets! We don't have a
698 // good way to do this today except by adding a nested loop.
699 // TODO(b/282025641): simplify this code once InputTargets are being identified
700 // separately from TouchedWindows.
701 std::erase_if(targets, [&](const InputTarget& target) {
702 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
703 });
704 return true;
705 }
706 return false;
707 });
708}
709
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700710/**
711 * In general, touch should be always split between windows. Some exceptions:
712 * 1. Don't split touch if all of the below is true:
713 * (a) we have an active pointer down *and*
714 * (b) a new pointer is going down that's from the same device *and*
715 * (c) the window that's receiving the current pointer does not support split touch.
716 * 2. Don't split mouse events
717 */
718bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
719 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
720 // We should never split mouse events
721 return false;
722 }
723 for (const TouchedWindow& touchedWindow : touchState.windows) {
724 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
725 // Spy windows should not affect whether or not touch is split.
726 continue;
727 }
728 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
729 continue;
730 }
731 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
732 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
733 // Wallpaper window should not affect whether or not touch is split
734 continue;
735 }
736
737 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
738 return false;
739 }
740 }
741 return true;
742}
743
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000744} // namespace
745
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746// --- InputDispatcher ---
747
Prabir Pradhana41d2442023-04-20 21:30:40 +0000748InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Garfield Tan00f511d2019-06-12 16:55:40 -0700749 : mPolicy(policy),
750 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700751 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800752 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700753 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700754 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700755 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800756 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700757 mDispatchEnabled(false),
758 mDispatchFrozen(false),
759 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100760 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000761 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800762 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000763 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000764 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700765 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800766 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700768 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700769#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700770 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700771#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700772 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773}
774
775InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000776 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777
Prabir Pradhancef936d2021-07-21 16:17:52 +0000778 resetKeyRepeatLocked();
779 releasePendingEventLocked();
780 drainInboundQueueLocked();
781 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000783 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700784 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000785 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787}
788
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700789status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700790 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700791 return ALREADY_EXISTS;
792 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700793 mThread = std::make_unique<InputThread>(
794 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
795 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700796}
797
798status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700799 if (mThread && mThread->isCallingThread()) {
800 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700801 return INVALID_OPERATION;
802 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700803 mThread.reset();
804 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700805}
806
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700808 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800810 std::scoped_lock _l(mLock);
811 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812
813 // Run a dispatch loop if there are no pending commands.
814 // The dispatch loop might enqueue commands to run afterwards.
815 if (!haveCommandsLocked()) {
816 dispatchOnceInnerLocked(&nextWakeupTime);
817 }
818
819 // Run all pending commands if there are any.
820 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000821 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700822 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800824
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700825 // If we are still waiting for ack on some events,
826 // we might have to wake up earlier to check if an app is anr'ing.
827 const nsecs_t nextAnrCheck = processAnrsLocked();
828 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
829
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800830 // We are about to enter an infinitely long sleep, because we have no commands or
831 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700832 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800833 mDispatcherEnteredIdle.notify_all();
834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 } // release lock
836
837 // Wait for callback or timeout or wake. (make sure we round up, not down)
838 nsecs_t currentTime = now();
839 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
840 mLooper->pollOnce(timeoutMillis);
841}
842
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500844 * Raise ANR if there is no focused window.
845 * Before the ANR is raised, do a final state check:
846 * 1. The currently focused application must be the same one we are waiting for.
847 * 2. Ensure we still don't have a focused window.
848 */
849void InputDispatcher::processNoFocusedWindowAnrLocked() {
850 // Check if the application that we are waiting for is still focused.
851 std::shared_ptr<InputApplicationHandle> focusedApplication =
852 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
853 if (focusedApplication == nullptr ||
854 focusedApplication->getApplicationToken() !=
855 mAwaitedFocusedApplication->getApplicationToken()) {
856 // Unexpected because we should have reset the ANR timer when focused application changed
857 ALOGE("Waited for a focused window, but focused application has already changed to %s",
858 focusedApplication->getName().c_str());
859 return; // The focused application has changed.
860 }
861
chaviw98318de2021-05-19 16:45:23 -0500862 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500863 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
864 if (focusedWindowHandle != nullptr) {
865 return; // We now have a focused window. No need for ANR.
866 }
867 onAnrLocked(mAwaitedFocusedApplication);
868}
869
870/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700871 * Check if any of the connections' wait queues have events that are too old.
872 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
873 * Return the time at which we should wake up next.
874 */
875nsecs_t InputDispatcher::processAnrsLocked() {
876 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700877 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700878 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
879 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
880 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500881 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700882 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500883 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700884 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700885 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500886 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700887 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
888 }
889 }
890
891 // Check if any connection ANRs are due
892 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
893 if (currentTime < nextAnrCheck) { // most likely scenario
894 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
895 }
896
897 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700898 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 if (connection == nullptr) {
900 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
901 return nextAnrCheck;
902 }
903 connection->responsive = false;
904 // Stop waking up for this unresponsive connection
905 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000906 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700907 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700908}
909
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800910std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700911 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800912 if (connection->monitor) {
913 return mMonitorDispatchingTimeout;
914 }
915 const sp<WindowInfoHandle> window =
916 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700917 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500918 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700919 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500920 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700921}
922
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
924 nsecs_t currentTime = now();
925
Jeff Browndc5992e2014-04-11 01:27:26 -0700926 // Reset the key repeat timer whenever normal dispatch is suspended while the
927 // device is in a non-interactive state. This is to ensure that we abort a key
928 // repeat if the device is just coming out of sleep.
929 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 resetKeyRepeatLocked();
931 }
932
933 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
934 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100935 if (DEBUG_FOCUS) {
936 ALOGD("Dispatch frozen. Waiting some more.");
937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 return;
939 }
940
941 // Optimize latency of app switches.
942 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
943 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700944 bool isAppSwitchDue;
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700945 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700946 isAppSwitchDue = mAppSwitchDueTime <= currentTime;
947 if (mAppSwitchDueTime < *nextWakeupTime) {
948 *nextWakeupTime = mAppSwitchDueTime;
949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 }
951
952 // Ready to start a new event.
953 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700955 if (mInboundQueue.empty()) {
Siarhei Vishniakou17f12282023-11-02 13:40:29 -0700956 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -0700957 if (isAppSwitchDue) {
958 // The inbound queue is empty so the app switch key we were waiting
959 // for will never arrive. Stop waiting for it.
960 resetPendingAppSwitchLocked(false);
961 isAppSwitchDue = false;
962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
964
965 // Synthesize a key repeat if appropriate.
966 if (mKeyRepeatState.lastKeyEntry) {
967 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
968 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
969 } else {
970 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
971 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
972 }
973 }
974 }
975
976 // Nothing to do if there is no pending event.
977 if (!mPendingEvent) {
978 return;
979 }
980 } else {
981 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700982 mPendingEvent = mInboundQueue.front();
983 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 traceInboundQueueLengthLocked();
985 }
986
987 // Poke user activity for this event.
988 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700989 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 }
992
993 // Now we have an event to dispatch.
994 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700995 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700997 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700999 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001001 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003
1004 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
1007
1008 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001009 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001010 const ConfigurationChangedEntry& typedEntry =
1011 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001013 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 break;
1015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 const DeviceResetEntry& typedEntry =
1019 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 break;
1023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001025 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001026 std::shared_ptr<const FocusEntry> typedEntry =
1027 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001028 dispatchFocusLocked(currentTime, typedEntry);
1029 done = true;
1030 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1031 break;
1032 }
1033
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001034 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001035 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001036 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1037 done = true;
1038 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1039 break;
1040 }
1041
Prabir Pradhan99987712020-11-10 18:43:05 -08001042 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1043 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001044 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001045 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1046 done = true;
1047 break;
1048 }
1049
arthurhungb89ccb02020-12-30 16:19:01 +08001050 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001051 std::shared_ptr<const DragEntry> typedEntry =
1052 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001053 dispatchDragLocked(currentTime, typedEntry);
1054 done = true;
1055 break;
1056 }
1057
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001058 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001059 std::shared_ptr<const KeyEntry> keyEntry =
1060 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001061 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001062 if (isAppSwitchDue) {
1063 if (isAppSwitchKeyEvent(*keyEntry)) {
1064 resetPendingAppSwitchLocked(true);
1065 isAppSwitchDue = false;
1066 } else if (dropReason == DropReason::NOT_DROPPED) {
1067 dropReason = DropReason::APP_SWITCH;
1068 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 }
1070 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1075 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001077 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 break;
1079 }
1080
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001081 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001082 std::shared_ptr<const MotionEntry> motionEntry =
1083 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001084 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001085 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1086 dropReason = DropReason::APP_SWITCH;
1087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001090 // The event is stale. However, only drop stale events if there isn't an ongoing
1091 // gesture. That would allow us to complete the processing of the current stroke.
1092 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1093 if (touchStateIt != mTouchStatesByDisplay.end()) {
1094 const TouchState& touchState = touchStateIt->second;
1095 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1096 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1097 dropReason = DropReason::STALE;
1098 }
1099 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001101 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1102 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001104 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 }
Chris Yef59a2f42020-10-16 12:55:26 -07001107
1108 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001109 std::shared_ptr<const SensorEntry> sensorEntry =
1110 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001111 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001112 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1113 dropReason = DropReason::APP_SWITCH;
1114 }
Chris Yef59a2f42020-10-16 12:55:26 -07001115 }
1116 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1117 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1118 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1119 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1120 dropReason = DropReason::STALE;
1121 }
1122 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1123 done = true;
1124 break;
1125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
1127
1128 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001130 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
Michael Wright3a981722015-06-10 15:26:13 +01001132 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133
1134 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001135 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
1137}
1138
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001139bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001140 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001141}
1142
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001143/**
1144 * Return true if the events preceding this incoming motion event should be dropped
1145 * Return false otherwise (the default behaviour)
1146 */
1147bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001148 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001149 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001150
1151 // Optimize case where the current application is unresponsive and the user
1152 // decides to touch a window in a different application.
1153 // If the application takes too long to catch up then we drop all events preceding
1154 // the touch into the other window.
1155 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001156 const int32_t displayId = motionEntry.displayId;
1157 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001158 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001159
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001160 sp<WindowInfoHandle> touchedWindowHandle =
1161 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001162 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001163 touchedWindowHandle->getApplicationToken() !=
1164 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001165 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001166 ALOGI("Pruning input queue because user touched a different application while waiting "
1167 "for %s",
1168 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001169 return true;
1170 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001171
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001172 // Alternatively, maybe there's a spy window that could handle this event.
1173 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1174 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1175 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001176 const std::shared_ptr<Connection> connection =
1177 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001178 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001179 // This spy window could take more input. Drop all events preceding this
1180 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001181 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001182 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001183 mAwaitedFocusedApplication->getName().c_str());
1184 return true;
1185 }
1186 }
1187 }
1188
1189 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1190 // yet been processed by some connections, the dispatcher will wait for these motion
1191 // events to be processed before dispatching the key event. This is because these motion events
1192 // may cause a new window to be launched, which the user might expect to receive focus.
1193 // To prevent waiting forever for such events, just send the key to the currently focused window
1194 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1195 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1196 "just send the pending key event to the focused window.");
1197 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001198 }
1199 return false;
1200}
1201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001205 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 traceInboundQueueLengthLocked();
1207
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001208 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001209 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001210 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1211 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 // Optimize app switch latency.
1213 // If the application takes too long to catch up then we drop all events preceding
1214 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001216
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07001217 if (!REMOVE_APP_SWITCH_DROPS) {
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001218 if (isAppSwitchKeyEvent(keyEntry)) {
1219 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
1220 mAppSwitchSawKeyDown = true;
1221 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
1222 if (mAppSwitchSawKeyDown) {
1223 if (DEBUG_APP_SWITCH) {
1224 ALOGD("App switch is pending!");
1225 }
1226 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
1227 mAppSwitchSawKeyDown = false;
1228 needWake = true;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001229 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001230 }
1231 }
1232 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001233 // If a new up event comes in, and the pending event with same key code has been asked
1234 // to try again later because of the policy. We have to reset the intercept key wake up
1235 // time for it may have been handled in the policy and could be dropped.
1236 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1237 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001238 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001239 if (pendingKey.keyCode == keyEntry.keyCode &&
1240 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001241 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1242 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001243 pendingKey.interceptKeyWakeupTime = 0;
1244 needWake = true;
1245 }
1246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 break;
1248 }
1249
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001250 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001251 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1252 "Unexpected untrusted event.");
Prabir Pradhan24047542023-11-02 17:14:59 +00001253 if (shouldPruneInboundQueueLocked(static_cast<const MotionEntry&>(entry))) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001255 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001259 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001260 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1261 break;
1262 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001263 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001264 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001265 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001266 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001267 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1268 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001269 // nothing to do
1270 break;
1271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273
1274 return needWake;
1275}
1276
Prabir Pradhan24047542023-11-02 17:14:59 +00001277void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001278 // Do not store sensor event in recent queue to avoid flooding the queue.
1279 if (entry->type != EventEntry::Type::SENSOR) {
1280 mRecentQueue.push_back(entry);
1281 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001282 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001283 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285}
1286
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001287sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1288 bool isStylus,
1289 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001291 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001292 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001293 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001294 continue;
1295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001297 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001298 if (!info.isSpy() &&
1299 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001300 return windowHandle;
1301 }
1302 }
1303 return nullptr;
1304}
1305
1306std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001307 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001308 if (touchedWindow == nullptr) {
1309 return {};
1310 }
1311 // Traverse windows from front to back until we encounter the touched window.
1312 std::vector<InputTarget> outsideTargets;
1313 const auto& windowHandles = getWindowHandlesLocked(displayId);
1314 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1315 if (windowHandle == touchedWindow) {
1316 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1317 // below the touched window will not get ACTION_OUTSIDE event.
1318 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001319 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001320
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001321 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001322 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001323 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1324 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001325 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1326 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001327 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 }
1329 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001330 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331}
1332
Prabir Pradhand65552b2021-10-07 11:23:50 -07001333std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001334 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001335 // Traverse windows from front to back and gather the touched spy windows.
1336 std::vector<sp<WindowInfoHandle>> spyWindows;
1337 const auto& windowHandles = getWindowHandlesLocked(displayId);
1338 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1339 const WindowInfo& info = *windowHandle->getInfo();
1340
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001341 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001342 continue;
1343 }
1344 if (!info.isSpy()) {
1345 // The first touched non-spy window was found, so return the spy windows touched so far.
1346 return spyWindows;
1347 }
1348 spyWindows.push_back(windowHandle);
1349 }
1350 return spyWindows;
1351}
1352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001353void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 const char* reason;
1355 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001356 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001357 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001358 ALOGD("Dropped event because policy consumed it.");
1359 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360 reason = "inbound event was dropped because the policy consumed it";
1361 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001362 case DropReason::DISABLED:
1363 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001364 ALOGI("Dropped event because input dispatch is disabled.");
1365 }
1366 reason = "inbound event was dropped because input dispatch is disabled";
1367 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001368 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001369 ALOGI("Dropped event because of pending overdue app switch.");
1370 reason = "inbound event was dropped because of pending overdue app switch";
1371 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001372 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373 ALOGI("Dropped event because the current application is not responding and the user "
1374 "has started interacting with a different application.");
1375 reason = "inbound event was dropped because the current application is not responding "
1376 "and the user has started interacting with a different application";
1377 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001379 ALOGI("Dropped event because it is stale.");
1380 reason = "inbound event was dropped because it is stale";
1381 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001382 case DropReason::NO_POINTER_CAPTURE:
1383 ALOGI("Dropped event because there is no window with Pointer Capture.");
1384 reason = "inbound event was dropped because there is no window with Pointer Capture";
1385 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001386 case DropReason::NOT_DROPPED: {
1387 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
1391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001393 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001394 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001398 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1400 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001401 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 synthesizeCancelationEventsForAllConnectionsLocked(options);
1403 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001404 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1405 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001406 synthesizeCancelationEventsForAllConnectionsLocked(options);
1407 }
1408 break;
1409 }
Chris Yef59a2f42020-10-16 12:55:26 -07001410 case EventEntry::Type::SENSOR: {
1411 break;
1412 }
arthurhungb89ccb02020-12-30 16:19:01 +08001413 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1414 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001415 break;
1416 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001417 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001418 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001419 case EventEntry::Type::CONFIGURATION_CHANGED:
1420 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001421 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001422 break;
1423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425}
1426
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001427static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1429 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430}
1431
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001432bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1433 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1434 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1435 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436}
1437
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001438bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001439 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440}
1441
1442void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001443 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001445 if (DEBUG_APP_SWITCH) {
1446 if (handled) {
1447 ALOGD("App switch has arrived.");
1448 } else {
1449 ALOGD("App switch was abandoned.");
1450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452}
1453
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001455 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456}
1457
Prabir Pradhancef936d2021-07-21 16:17:52 +00001458bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001459 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 return false;
1461 }
1462
1463 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001464 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001465 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001466 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1467 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 return true;
1470}
1471
Prabir Pradhancef936d2021-07-21 16:17:52 +00001472void InputDispatcher::postCommandLocked(Command&& command) {
1473 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474}
1475
1476void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001477 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001478 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001479 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 releaseInboundEventLocked(entry);
1481 }
1482 traceInboundQueueLengthLocked();
1483}
1484
1485void InputDispatcher::releasePendingEventLocked() {
1486 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 }
1490}
1491
Prabir Pradhan24047542023-11-02 17:14:59 +00001492void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001493 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001494 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001495 if (DEBUG_DISPATCH_CYCLE) {
1496 ALOGD("Injected inbound event was dropped.");
1497 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001498 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001501 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504}
1505
1506void InputDispatcher::resetKeyRepeatLocked() {
1507 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001508 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510}
1511
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001512std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001513 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514
Michael Wright2e732952014-09-24 13:26:59 -07001515 uint32_t policyFlags = entry->policyFlags &
1516 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001519 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1520 currentTime, entry->deviceId, entry->source,
1521 entry->displayId, policyFlags, entry->action, entry->flags,
1522 entry->keyCode, entry->scanCode, entry->metaState,
1523 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001525 newEntry->syntheticRepeat = true;
1526 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001528 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529}
1530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001531bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001532 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001533 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1534 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536
1537 // Reset key repeating in case a keyboard device was added or removed or something.
1538 resetKeyRepeatLocked();
1539
1540 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001541 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1542 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001543 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001544 };
1545 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 return true;
1547}
1548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1550 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001551 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1552 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1553 entry.deviceId);
1554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555
liushenxiang42232912021-05-21 20:24:09 +08001556 // Reset key repeating in case a keyboard device was disabled or enabled.
1557 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1558 resetKeyRepeatLocked();
1559 }
1560
Michael Wrightfb04fd52022-11-24 22:31:11 +00001561 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001564
1565 // Remove all active pointers from this device
1566 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1567 touchState.removeAllPointersForDevice(entry.deviceId);
1568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 return true;
1570}
1571
Vishnu Nairad321cd2020-08-20 16:40:21 -07001572void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001573 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001574 if (mPendingEvent != nullptr) {
1575 // Move the pending event to the front of the queue. This will give the chance
1576 // for the pending event to get dispatched to the newly focused window
1577 mInboundQueue.push_front(mPendingEvent);
1578 mPendingEvent = nullptr;
1579 }
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 std::unique_ptr<FocusEntry> focusEntry =
1582 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1583 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001584
1585 // This event should go to the front of the queue, but behind all other focus events
1586 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001587 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1588 [](const std::shared_ptr<const EventEntry>& event) {
1589 return event->type == EventEntry::Type::FOCUS;
1590 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001591
1592 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001594}
1595
Prabir Pradhan24047542023-11-02 17:14:59 +00001596void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1597 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001598 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001599 if (channel == nullptr) {
1600 return; // Window has gone away
1601 }
1602 InputTarget target;
1603 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001604 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001605 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1606 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001607 std::string reason = std::string("reason=").append(entry->reason);
1608 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001609 dispatchEventLocked(currentTime, entry, {target});
1610}
1611
Prabir Pradhan99987712020-11-10 18:43:05 -08001612void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001613 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001614 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001615 dropReason = DropReason::NOT_DROPPED;
1616
Prabir Pradhan99987712020-11-10 18:43:05 -08001617 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001618 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001619
1620 if (entry->pointerCaptureRequest.enable) {
1621 // Enable Pointer Capture.
1622 if (haveWindowWithPointerCapture &&
1623 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001624 // This can happen if pointer capture is disabled and re-enabled before we notify the
1625 // app of the state change, so there is no need to notify the app.
1626 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1627 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001628 }
1629 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001630 // This can happen if a window requests capture and immediately releases capture.
1631 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001632 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001633 return;
1634 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001635 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1636 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1637 return;
1638 }
1639
Vishnu Nairc519ff72021-01-21 08:23:08 -08001640 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001641 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1642 mWindowTokenWithPointerCapture = token;
1643 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001644 // Disable Pointer Capture.
1645 // We do not check if the sequence number matches for requests to disable Pointer Capture
1646 // for two reasons:
1647 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1648 // to disable capture with the same sequence number: one generated by
1649 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1650 // Capture being disabled in InputReader.
1651 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1652 // actual Pointer Capture state that affects events being generated by input devices is
1653 // in InputReader.
1654 if (!haveWindowWithPointerCapture) {
1655 // Pointer capture was already forcefully disabled because of focus change.
1656 dropReason = DropReason::NOT_DROPPED;
1657 return;
1658 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001659 token = mWindowTokenWithPointerCapture;
1660 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001661 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001662 setPointerCaptureLocked(false);
1663 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 }
1665
1666 auto channel = getInputChannelLocked(token);
1667 if (channel == nullptr) {
1668 // Window has gone away, clean up Pointer Capture state.
1669 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001670 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001671 setPointerCaptureLocked(false);
1672 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001673 return;
1674 }
1675 InputTarget target;
1676 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001677 entry->dispatchInProgress = true;
1678 dispatchEventLocked(currentTime, entry, {target});
1679
1680 dropReason = DropReason::NOT_DROPPED;
1681}
1682
Prabir Pradhan24047542023-11-02 17:14:59 +00001683void InputDispatcher::dispatchTouchModeChangeLocked(
1684 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001685 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;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001713 inputTargets.push_back(target);
1714 }
1715 return inputTargets;
1716}
1717
Prabir Pradhan24047542023-11-02 17:14:59 +00001718bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001719 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001721 if (!entry->dispatchInProgress) {
1722 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1723 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1724 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1725 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001726 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 // We have seen two identical key downs in a row which indicates that the device
1728 // driver is automatically generating key repeats itself. We take note of the
1729 // repeat here, but we disable our own next key repeat timer since it is clear that
1730 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001731 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1732 // Make sure we don't get key down from a different device. If a different
1733 // device Id has same key pressed down, the new device Id will replace the
1734 // current one to hold the key repeat with repeat count reset.
1735 // In the future when got a KEY_UP on the device id, drop it and do not
1736 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1738 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001739 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 } else {
1741 // Not a repeat. Save key down state in case we do see a repeat later.
1742 resetKeyRepeatLocked();
1743 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1744 }
1745 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001746 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1747 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001748 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001749 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001750 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1751 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 resetKeyRepeatLocked();
1754 }
1755
1756 if (entry->repeatCount == 1) {
1757 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1758 } else {
1759 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1760 }
1761
1762 entry->dispatchInProgress = true;
1763
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001764 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
1766
1767 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001768 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 if (currentTime < entry->interceptKeyWakeupTime) {
1770 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1771 *nextWakeupTime = entry->interceptKeyWakeupTime;
1772 }
1773 return false; // wait until next wakeup
1774 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001775 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 entry->interceptKeyWakeupTime = 0;
1777 }
1778
1779 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001780 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001782 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001783 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001784
1785 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1786 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1787 };
1788 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001789 // Poke user activity for keys not passed to user
1790 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 return false; // wait for the command to run
1792 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001793 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001795 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001796 if (*dropReason == DropReason::NOT_DROPPED) {
1797 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 }
1799 }
1800
1801 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001802 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001803 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1805 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001806 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001807 // Poke user activity for undispatched keys
1808 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 return true;
1810 }
1811
1812 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001813 InputEventInjectionResult injectionResult;
1814 sp<WindowInfoHandle> focusedWindow =
1815 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1816 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001817 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 return false;
1819 }
1820
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001821 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 return true;
1824 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001825 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1826
1827 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001828 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1829 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001831 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001832 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833
1834 // Dispatch the key.
1835 dispatchEventLocked(currentTime, entry, inputTargets);
1836 return true;
1837}
1838
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001839void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001840 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1841 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1842 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1843 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1844 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1845 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1846 entry.metaState, entry.repeatCount, entry.downTime);
1847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848}
1849
Prabir Pradhancef936d2021-07-21 16:17:52 +00001850void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001851 const std::shared_ptr<const SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001852 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001853 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1854 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1855 "source=0x%x, sensorType=%s",
1856 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001857 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001858 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001859 auto command = [this, entry]() REQUIRES(mLock) {
1860 scoped_unlock unlock(mLock);
1861
1862 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001863 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001864 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001865 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1866 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001867 };
1868 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001869}
1870
1871bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001872 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1873 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001874 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001875 }
Chris Yef59a2f42020-10-16 12:55:26 -07001876 { // acquire lock
1877 std::scoped_lock _l(mLock);
1878
1879 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001880 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001881 if (entry->type == EventEntry::Type::SENSOR) {
1882 it = mInboundQueue.erase(it);
1883 releaseInboundEventLocked(entry);
1884 }
1885 }
1886 }
1887 return true;
1888}
1889
Prabir Pradhan24047542023-11-02 17:14:59 +00001890bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1891 std::shared_ptr<const MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001893 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001895 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 entry->dispatchInProgress = true;
1897
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001898 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
1900
1901 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001902 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001903 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1905 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 return true;
1907 }
1908
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001909 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
1911 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001912 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 if (isPointerEvent) {
1916 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001917
1918 if (mDragState &&
1919 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1920 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1921 pilferPointersLocked(mDragState->dragWindow->getToken());
1922 }
1923
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001924 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001925 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001926 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1927 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 } else {
1929 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001930 sp<WindowInfoHandle> focusedWindow =
1931 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1932 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1933 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001934 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1935 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1936 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 return false;
1941 }
1942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001943 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001944 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 return true;
1946 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001948 CancelationOptions::Mode mode(
1949 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1950 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001951 CancelationOptions options(mode, "input event injection failed");
1952 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 return true;
1954 }
1955
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001956 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001957 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
1959 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 dispatchEventLocked(currentTime, entry, inputTargets);
1961 return true;
1962}
1963
chaviw98318de2021-05-19 16:45:23 -05001964void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001965 bool isExiting, const int32_t rawX,
1966 const int32_t rawY) {
1967 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001968 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001969 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1970 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001971
1972 enqueueInboundEventLocked(std::move(dragEntry));
1973}
1974
Prabir Pradhan24047542023-11-02 17:14:59 +00001975void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
1976 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08001977 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1978 if (channel == nullptr) {
1979 return; // Window has gone away
1980 }
1981 InputTarget target;
1982 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08001983 entry->dispatchInProgress = true;
1984 dispatchEventLocked(currentTime, entry, {target});
1985}
1986
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001988 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001989 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001990 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001991 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001992 "metaState=0x%x, buttonState=0x%x,"
1993 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001994 prefix, entry.eventTime, entry.deviceId,
1995 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1996 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1997 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1998 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002000 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002001 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002002 "x=%f, y=%f, pressure=%f, size=%f, "
2003 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2004 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002005 i, entry.pointerProperties[i].id,
2006 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002007 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2015 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018}
2019
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002020void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002021 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002022 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002023 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002024 if (DEBUG_DISPATCH_CYCLE) {
2025 ALOGD("dispatchEventToCurrentInputTargets");
2026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002028 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002029
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2031
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002034 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002035 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002036 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002037 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002038 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002040 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2041 LOG(INFO) << "Dropping event delivery to target with channel "
2042 << inputTarget.inputChannel->getName()
2043 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 }
2046 }
2047}
2048
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002049void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2051 // If the policy decides to close the app, we will get a channel removal event via
2052 // unregisterInputChannel, and will clean up the connection that way. We are already not
2053 // sending new pointers to the connection when it blocked, but focused events will continue to
2054 // pile up.
2055 ALOGW("Canceling events for %s because it is unresponsive",
2056 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002057 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002058 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002059 "application not responding");
2060 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 }
2062}
2063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002065 if (DEBUG_FOCUS) {
2066 ALOGD("Resetting ANR timeouts.");
2067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068
2069 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002070 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002071 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072}
2073
Tiger Huang721e26f2018-07-24 22:26:19 +08002074/**
2075 * Get the display id that the given event should go to. If this event specifies a valid display id,
2076 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2077 * Focused display is the display that the user most recently interacted with.
2078 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002079int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002080 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002081 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002082 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002083 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2084 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 break;
2086 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002087 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002088 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2089 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002090 break;
2091 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002092 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002093 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002094 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002095 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002096 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002097 case EventEntry::Type::SENSOR:
2098 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002099 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002100 return ADISPLAY_ID_NONE;
2101 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002102 }
2103 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2104}
2105
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002106bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2107 const char* focusedWindowName) {
2108 if (mAnrTracker.empty()) {
2109 // already processed all events that we waited for
2110 mKeyIsWaitingForEventsTimeout = std::nullopt;
2111 return false;
2112 }
2113
2114 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2115 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002116 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002117 mKeyIsWaitingForEventsTimeout = currentTime +
2118 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2119 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 return true;
2121 }
2122
2123 // We still have pending events, and already started the timer
2124 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2125 return true; // Still waiting
2126 }
2127
2128 // Waited too long, and some connection still hasn't processed all motions
2129 // Just send the key to the focused window
2130 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2131 focusedWindowName);
2132 mKeyIsWaitingForEventsTimeout = std::nullopt;
2133 return false;
2134}
2135
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002136sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2137 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2138 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002139 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002140 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141
Tiger Huang721e26f2018-07-24 22:26:19 +08002142 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002143 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002144 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002145 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2146
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 // If there is no currently focused window and no focused application
2148 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002149 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2150 ALOGI("Dropping %s event because there is no focused window or focused application in "
2151 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002152 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002153 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155
Vishnu Nair062a8672021-09-03 16:07:44 -07002156 // Drop key events if requested by input feature
2157 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002159 }
2160
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2162 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2163 // start interacting with another application via touch (app switch). This code can be removed
2164 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2165 // an app is expected to have a focused window.
2166 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2167 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2168 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002169 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2170 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2171 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002172 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002173 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 ALOGW("Waiting because no window has focus but %s may eventually add a "
2175 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002176 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002178 outInjectionResult = InputEventInjectionResult::PENDING;
2179 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002180 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2181 // Already raised ANR. Drop the event
2182 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002183 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002184 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002185 } else {
2186 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002187 outInjectionResult = InputEventInjectionResult::PENDING;
2188 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002189 }
2190 }
2191
2192 // we have a valid, non-null focused window
2193 resetNoFocusedWindowTimeoutLocked();
2194
Prabir Pradhan5735a322022-04-11 17:23:34 +00002195 // Verify targeted injection.
2196 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2197 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002198 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2199 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002202 if (focusedWindowHandle->getInfo()->inputConfig.test(
2203 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002204 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002205 outInjectionResult = InputEventInjectionResult::PENDING;
2206 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002207 }
2208
2209 // If the event is a key event, then we must wait for all previous events to
2210 // complete before delivering it because previous events may have the
2211 // side-effect of transferring focus to a different window and we want to
2212 // ensure that the following keys are sent to the new window.
2213 //
2214 // Suppose the user touches a button in a window then immediately presses "A".
2215 // If the button causes a pop-up window to appear then we want to ensure that
2216 // the "A" key is delivered to the new pop-up window. This is because users
2217 // often anticipate pending UI changes when typing on a keyboard.
2218 // To obtain this behavior, we must serialize key events with respect to all
2219 // prior input events.
2220 if (entry.type == EventEntry::Type::KEY) {
2221 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2222 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002223 outInjectionResult = InputEventInjectionResult::PENDING;
2224 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
2227
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002228 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2229 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230}
2231
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002232/**
2233 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2234 * that are currently unresponsive.
2235 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002236std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2237 const std::vector<Monitor>& monitors) const {
2238 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002239 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002240 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002241 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002242 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 if (connection == nullptr) {
2244 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002245 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 return false;
2247 }
2248 if (!connection->responsive) {
2249 ALOGW("Unresponsive monitor %s will not get the new gesture",
2250 connection->inputChannel->getName().c_str());
2251 return false;
2252 }
2253 return true;
2254 });
2255 return responsiveMonitors;
2256}
2257
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002258std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002259 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002260 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002261 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002263 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 // For security reasons, we defer updating the touch state until we are sure that
2265 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002266 const int32_t displayId = entry.displayId;
2267 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002268 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269
2270 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002271 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002273 // Copy current touch state into tempTouchState.
2274 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2275 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002276 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002277 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002278 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2279 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002280 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002281 }
2282
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002283 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002284
2285 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2286 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2287 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002288 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2289 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002290 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002291 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2292 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002293 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2294 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2295 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002296 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002297
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002298 if (newGesture) {
2299 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002300 }
2301
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002302 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2303 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2304 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002307 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002308 if (wasDown) {
2309 // Started hovering, but the device is already down: reject the hover event
2310 LOG(ERROR) << "Got hover event " << entry.getDescription()
2311 << " but the device is already down " << oldState->dump();
2312 outInjectionResult = InputEventInjectionResult::FAILED;
2313 return {};
2314 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002315 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2316 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002317 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002318 }
2319
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2321 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002322 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002323 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002324 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002325 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2326 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002327 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002328 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002329 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002330
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002331 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002332 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002335 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002336 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002338 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002339 }
2340
Prabir Pradhan5735a322022-04-11 17:23:34 +00002341 // Verify targeted injection.
2342 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2343 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002344 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002345 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002346 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002347 }
2348
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002349 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002350 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2352 // New window supports splitting, but we should never split mouse events.
2353 isSplit = !isFromMouse;
2354 } else if (isSplit) {
2355 // New window does not support splitting but we have already split events.
2356 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002357 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2358 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002359 newTouchedWindowHandle = nullptr;
2360 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002361 } else {
2362 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002363 // be delivered to a new window which supports split touch. Pointers from a mouse device
2364 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002365 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002366 }
2367
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002368 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002369 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002370 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002371 // Process the foreground window first so that it is the first to receive the event.
2372 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 }
2374
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002375 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002376 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2377 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002378 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002379 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002380 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002381 }
2382
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002384 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 continue;
2386 }
2387
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002388 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002389 // The "windowHandle" is the target of this hovering pointer.
2390 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002391 }
2392
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002394 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002395
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002396 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2397 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002398 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002399 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400
2401 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002402 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002403 }
2404 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002405 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002406 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002407 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002409
2410 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002411
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002412 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002413 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002414 pointerIds.set(pointerId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002415 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2416 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002417 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
2418 targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002419 isDownOrPointerDown
2420 ? std::make_optional(entry.eventTime)
2421 : std::nullopt);
2422 // If this is the pointer going down and the touched window has a wallpaper
2423 // then also add the touched wallpaper windows so they are locked in for the
2424 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2425 // SCROLL because the wallpaper engine only supports touch events. We would need to
2426 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2427 // handle these events.
2428 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002429 windowHandle->getInfo()->inputConfig.test(
2430 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2431 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2432 if (wallpaper != nullptr) {
2433 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2434 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002435 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002436 if (isSplit) {
2437 wallpaperFlags |= InputTarget::Flags::SPLIT;
2438 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002439 tempTouchState.addOrUpdateWindow(wallpaper,
2440 InputTarget::DispatchMode::AS_IS,
2441 wallpaperFlags, entry.deviceId, pointerIds,
2442 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002443 }
2444 }
2445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002447
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002448 // If a window is already pilfering some pointers, give it this new pointer as well and
2449 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2450 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002451 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002452 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2453 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002454 // This window is already pilfering some pointers, and this new pointer is also
2455 // going to it. Therefore, take over this pointer and don't give it to anyone
2456 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002457 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002458 }
2459 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002460
2461 // Restrict all pilfered pointers to the pilfering windows.
2462 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 } else {
2464 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2465
2466 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002467 if (!tempTouchState.isDown(entry.deviceId) &&
2468 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002469 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2470 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2471 << " is not down or we previously dropped the pointer down event in "
2472 << "display " << displayId << ": " << entry.getDescription();
2473 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002474 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002475 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 }
2477
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002478 // If the pointer is not currently hovering, then ignore the event.
2479 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2480 const int32_t pointerId = entry.pointerProperties[0].id;
2481 if (oldState == nullptr ||
2482 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2483 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2484 "display "
2485 << displayId << ": " << entry.getDescription();
2486 outInjectionResult = InputEventInjectionResult::FAILED;
2487 return {};
2488 }
2489 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2490 }
2491
arthurhung6d4bed92021-03-17 11:59:33 +08002492 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002493
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002495 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002496 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002497 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002498 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002499 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002500 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002501 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002502 sp<WindowInfoHandle> newTouchedWindowHandle =
2503 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002504
Prabir Pradhan5735a322022-04-11 17:23:34 +00002505 // Verify targeted injection.
2506 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2507 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002508 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002509 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002510 }
2511
Vishnu Nair062a8672021-09-03 16:07:44 -07002512 // Drop touch events if requested by input feature
2513 if (newTouchedWindowHandle != nullptr &&
2514 shouldDropInput(entry, newTouchedWindowHandle)) {
2515 newTouchedWindowHandle = nullptr;
2516 }
2517
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002518 if (newTouchedWindowHandle != nullptr &&
2519 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002520 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002521 oldTouchedWindowHandle->getName().c_str(),
2522 newTouchedWindowHandle->getName().c_str(), displayId);
2523
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002525 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002526 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002527 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002528
2529 const TouchedWindow& touchedWindow =
2530 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002531 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002532 InputTarget::DispatchMode::SLIPPERY_EXIT,
2533 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002534 touchedWindow.getDownTimeInTarget(entry.deviceId),
2535 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536
2537 // Make a slippery entrance into the new window.
2538 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002539 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002542 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002543 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002544 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002547 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002550 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002551 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002552 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 }
2554
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002555 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2556 InputTarget::DispatchMode::SLIPPERY_ENTER,
2557 targetFlags, entry.deviceId, pointerIds,
2558 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002559
2560 // Check if the wallpaper window should deliver the corresponding event.
2561 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002562 tempTouchState, entry.deviceId, pointerId, targets);
2563 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2564 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566 }
Arthur Hung96483742022-11-15 03:30:48 +00002567
2568 // Update the pointerIds for non-splittable when it received pointer down.
2569 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2570 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002571 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002572 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2573 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2574 // Ignore drag window for it should just track one pointer.
2575 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2576 continue;
2577 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002578 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2579 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2580 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002581 }
2582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 }
2584
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002585 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002586 {
2587 std::vector<TouchedWindow> hoveringWindows =
2588 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2589 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002590 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002591 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2592 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002593 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002594 if (!target) {
2595 continue;
2596 }
2597 // Hardcode to single hovering pointer for now.
2598 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2599 pointerIds.set(entry.pointerProperties[0].id);
2600 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2601 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Prabir Pradhan5735a322022-04-11 17:23:34 +00002605 // Ensure that all touched windows are valid for injection.
2606 if (entry.injectionState != nullptr) {
2607 std::string errs;
2608 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002609 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2610 if (err) errs += "\n - " + *err;
2611 }
2612 if (!errs.empty()) {
2613 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002614 "%s:%s",
2615 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002616 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002617 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002618 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002619 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002620
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002621 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2622 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002624 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002625 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002626 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002627 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002628 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002629 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002630 sp<WindowInfoHandle> targetWindow =
2631 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2632 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2633 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 }
2636 }
2637 }
2638 }
2639
Harry Cuttsb166c002023-05-09 13:06:05 +00002640 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2641 // only want the system UI to handle these gestures.
2642 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2643 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2644 if (isTouchpadNavGesture) {
2645 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2646 }
2647
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002648 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002649 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002650 std::bitset<MAX_POINTER_ID + 1> touchingPointers =
2651 touchedWindow.getTouchingPointers(entry.deviceId);
2652 if (touchingPointers.none()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002653 continue;
2654 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002655 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2656 touchedWindow.targetFlags, touchingPointers,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002657 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002658 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002659
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002660 // During targeted injection, only allow owned targets to receive events
2661 std::erase_if(targets, [&](const InputTarget& target) {
2662 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2663 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2664 if (err) {
2665 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2666 << ": " << (*err);
2667 return true;
2668 }
2669 return false;
2670 });
2671
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002672 if (targets.empty()) {
2673 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2674 outInjectionResult = InputEventInjectionResult::FAILED;
2675 return {};
2676 }
2677
2678 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2679 // window that is actually receiving the entire gesture.
2680 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002681 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002682 })) {
2683 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2684 << entry.getDescription();
2685 outInjectionResult = InputEventInjectionResult::FAILED;
2686 return {};
2687 }
2688
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002689 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690
Prabir Pradhan502a7252023-12-01 16:11:24 +00002691 // Now that we have generated all of the input targets for this event, reset the dispatch
2692 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002693 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002694 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002695 }
2696
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002697 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002698 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002699 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002700 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002701 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002702 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002703 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002704 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2705 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002706 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2707 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2708 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 }
2710
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002711 // Save changes unless the action was scroll in which case the temporary touch
2712 // state was only valid for this one action.
2713 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002714 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002715 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002716 mTouchStatesByDisplay[displayId] = tempTouchState;
2717 } else {
2718 mTouchStatesByDisplay.erase(displayId);
2719 }
2720 }
2721
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002722 if (tempTouchState.windows.empty()) {
2723 mTouchStatesByDisplay.erase(displayId);
2724 }
2725
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002726 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727}
2728
arthurhung6d4bed92021-03-17 11:59:33 +08002729void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002730 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2731 // have an explicit reason to support it.
2732 constexpr bool isStylus = false;
2733
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002734 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002735 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002736 if (dropWindow) {
2737 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002738 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002739 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002740 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002741 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002742 }
2743 mDragState.reset();
2744}
2745
2746void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002747 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002748 return;
2749 }
2750
arthurhung6d4bed92021-03-17 11:59:33 +08002751 if (!mDragState->isStartDrag) {
2752 mDragState->isStartDrag = true;
2753 mDragState->isStylusButtonDownAtStart =
2754 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2755 }
2756
Arthur Hung54745652022-04-20 07:17:41 +00002757 // Find the pointer index by id.
2758 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002759 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002760 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2761 if (pointerProperties.id == mDragState->pointerId) {
2762 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002763 }
Arthur Hung54745652022-04-20 07:17:41 +00002764 }
arthurhung6d4bed92021-03-17 11:59:33 +08002765
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002766 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002767 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002768 }
2769
2770 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2771 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2772 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2773
2774 switch (maskedAction) {
2775 case AMOTION_EVENT_ACTION_MOVE: {
2776 // Handle the special case : stylus button no longer pressed.
2777 bool isStylusButtonDown =
2778 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2779 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2780 finishDragAndDrop(entry.displayId, x, y);
2781 return;
2782 }
2783
2784 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2785 // until we have an explicit reason to support it.
2786 constexpr bool isStylus = false;
2787
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002788 sp<WindowInfoHandle> hoverWindowHandle =
2789 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2790 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002791 // enqueue drag exit if needed.
2792 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2793 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2794 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002795 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002796 y);
2797 }
2798 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2799 }
2800 // enqueue drag location if needed.
2801 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002802 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002803 }
2804 break;
2805 }
2806
2807 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002808 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002809 break;
2810 }
2811 // The drag pointer is up.
2812 [[fallthrough]];
2813 case AMOTION_EVENT_ACTION_UP:
2814 finishDragAndDrop(entry.displayId, x, y);
2815 break;
2816 case AMOTION_EVENT_ACTION_CANCEL: {
2817 ALOGD("Receiving cancel when drag and drop.");
2818 sendDropWindowCommandLocked(nullptr, 0, 0);
2819 mDragState.reset();
2820 break;
2821 }
arthurhungb89ccb02020-12-30 16:19:01 +08002822 }
2823}
2824
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002825std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2826 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002827 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002828 std::optional<nsecs_t> firstDownTimeInTarget) const {
2829 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2830 if (inputChannel == nullptr) {
2831 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2832 return {};
2833 }
2834 InputTarget inputTarget;
2835 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002836 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002837 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002838 inputTarget.flags = targetFlags;
2839 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2840 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2841 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2842 if (displayInfoIt != mDisplayInfos.end()) {
2843 inputTarget.displayTransform = displayInfoIt->second.transform;
2844 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002845 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002846 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2847 }
2848 return inputTarget;
2849}
2850
chaviw98318de2021-05-19 16:45:23 -05002851void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002852 InputTarget::DispatchMode dispatchMode,
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 =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002867 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2868 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002869 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002870 return;
2871 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002873 it = inputTargets.end() - 1;
2874 }
2875
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002876 if (it->flags != targetFlags) {
2877 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2878 }
2879 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2880 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2881 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2882 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002883}
2884
2885void InputDispatcher::addPointerWindowTargetLocked(
2886 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002887 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2888 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2889 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002890 if (pointerIds.none()) {
2891 for (const auto& target : inputTargets) {
2892 LOG(INFO) << "Target: " << target;
2893 }
2894 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2895 return;
2896 }
2897 std::vector<InputTarget>::iterator it =
2898 std::find_if(inputTargets.begin(), inputTargets.end(),
2899 [&windowHandle](const InputTarget& inputTarget) {
2900 return inputTarget.inputChannel->getConnectionToken() ==
2901 windowHandle->getToken();
2902 });
2903
2904 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2905 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2906 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2907 // input targets for hovering pointers and for touching pointers.
2908 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2909 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002910 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002911 // Force the code below to create a new input target
2912 it = inputTargets.end();
2913 }
2914
2915 const WindowInfo* windowInfo = windowHandle->getInfo();
2916
2917 if (it == inputTargets.end()) {
2918 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002919 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2920 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002921 if (!target) {
2922 return;
2923 }
2924 inputTargets.push_back(*target);
2925 it = inputTargets.end() - 1;
2926 }
2927
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002928 if (it->dispatchMode != dispatchMode) {
2929 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2930 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2931 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002932 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002933 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2934 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002935 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002936 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002937 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002938 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2939 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002940
chaviw1ff3d1e2020-07-01 15:53:47 -07002941 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942}
2943
Michael Wright3dd60e22019-03-27 22:06:44 +00002944void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002945 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002946 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2947 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002948
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002949 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2950 InputTarget target;
2951 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002952 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2953 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002954 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2955 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002956 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002957 target.setDefaultPointerTransform(target.displayTransform);
2958 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 }
2960}
2961
Robert Carrc9bf1d32020-04-13 17:21:08 -07002962/**
2963 * Indicate whether one window handle should be considered as obscuring
2964 * another window handle. We only check a few preconditions. Actually
2965 * checking the bounds is left to the caller.
2966 */
chaviw98318de2021-05-19 16:45:23 -05002967static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2968 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002969 // Compare by token so cloned layers aren't counted
2970 if (haveSameToken(windowHandle, otherHandle)) {
2971 return false;
2972 }
2973 auto info = windowHandle->getInfo();
2974 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002975 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002976 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002977 } else if (otherInfo->alpha == 0 &&
2978 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002979 // Those act as if they were invisible, so we don't need to flag them.
2980 // We do want to potentially flag touchable windows even if they have 0
2981 // opacity, since they can consume touches and alter the effects of the
2982 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002983 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002984 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2985 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002986 } else if (info->ownerUid == otherInfo->ownerUid) {
2987 // If ownerUid is the same we don't generate occlusion events as there
2988 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002989 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002990 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002991 return false;
2992 } else if (otherInfo->displayId != info->displayId) {
2993 return false;
2994 }
2995 return true;
2996}
2997
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002998/**
2999 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3000 * untrusted, one should check:
3001 *
3002 * 1. If result.hasBlockingOcclusion is true.
3003 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3004 * BLOCK_UNTRUSTED.
3005 *
3006 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3007 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3008 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3009 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3010 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3011 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3012 *
3013 * If neither of those is true, then it means the touch can be allowed.
3014 */
3015InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003016 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3017 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003018 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003019 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003020 TouchOcclusionInfo info;
3021 info.hasBlockingOcclusion = false;
3022 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003023 info.obscuringUid = gui::Uid::INVALID;
3024 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003025 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003026 if (windowHandle == otherHandle) {
3027 break; // All future windows are below us. Exit early.
3028 }
chaviw98318de2021-05-19 16:45:23 -05003029 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003030 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3031 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003032 if (DEBUG_TOUCH_OCCLUSION) {
3033 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003034 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003035 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003036 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3037 // we perform the checks below to see if the touch can be propagated or not based on the
3038 // window's touch occlusion mode
3039 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3040 info.hasBlockingOcclusion = true;
3041 info.obscuringUid = otherInfo->ownerUid;
3042 info.obscuringPackage = otherInfo->packageName;
3043 break;
3044 }
3045 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003046 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003047 float opacity =
3048 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3049 // Given windows A and B:
3050 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3051 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3052 opacityByUid[uid] = opacity;
3053 if (opacity > info.obscuringOpacity) {
3054 info.obscuringOpacity = opacity;
3055 info.obscuringUid = uid;
3056 info.obscuringPackage = otherInfo->packageName;
3057 }
3058 }
3059 }
3060 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003061 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003062 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003063 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003064 return info;
3065}
3066
chaviw98318de2021-05-19 16:45:23 -05003067std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003068 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003069 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003070 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3071 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3072 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003073 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003074 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003075 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3076 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003077 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3078 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3079 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003080 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003081}
3082
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003083bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3084 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003085 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3086 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003087 return false;
3088 }
3089 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003090 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003091 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003092 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003093 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3094 return false;
3095 }
3096 return true;
3097}
3098
chaviw98318de2021-05-19 16:45:23 -05003099bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003102 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3103 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003104 if (windowHandle == otherHandle) {
3105 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 }
chaviw98318de2021-05-19 16:45:23 -05003107 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003108 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003109 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 return true;
3111 }
3112 }
3113 return false;
3114}
3115
chaviw98318de2021-05-19 16:45:23 -05003116bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003117 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003118 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3119 const WindowInfo* windowInfo = windowHandle->getInfo();
3120 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003121 if (windowHandle == otherHandle) {
3122 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003123 }
chaviw98318de2021-05-19 16:45:23 -05003124 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003125 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003126 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003127 return true;
3128 }
3129 }
3130 return false;
3131}
3132
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003133std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003134 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003135 if (applicationHandle != nullptr) {
3136 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003137 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 } else {
3139 return applicationHandle->getName();
3140 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003141 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003142 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003144 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 }
3146}
3147
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003148void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003149 if (!isUserActivityEvent(eventEntry)) {
3150 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003151 return;
3152 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003153 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003154 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003155 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003156 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003157 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003158 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003159 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161 }
3162
3163 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003164 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003165 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003166 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3167 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 return;
3169 }
Josep del Riob3981622023-04-18 15:49:45 +00003170 if (windowDisablingUserActivityInfo != nullptr) {
3171 if (DEBUG_DISPATCH_CYCLE) {
3172 ALOGD("Not poking user activity: disabled by window '%s'.",
3173 windowDisablingUserActivityInfo->name.c_str());
3174 }
3175 return;
3176 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003177 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 eventType = USER_ACTIVITY_EVENT_TOUCH;
3179 }
3180 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003182 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003183 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3184 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185 return;
3186 }
Josep del Riob3981622023-04-18 15:49:45 +00003187 // If the key code is unknown, we don't consider it user activity
3188 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3189 return;
3190 }
3191 // Don't inhibit events that were intercepted or are not passed to
3192 // the apps, like system shortcuts
3193 if (windowDisablingUserActivityInfo != nullptr &&
3194 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3195 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3196 if (DEBUG_DISPATCH_CYCLE) {
3197 ALOGD("Not poking user activity: disabled by window '%s'.",
3198 windowDisablingUserActivityInfo->name.c_str());
3199 }
3200 return;
3201 }
3202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 eventType = USER_ACTIVITY_EVENT_BUTTON;
3204 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003206 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003207 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003208 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003209 break;
3210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 }
3212
Prabir Pradhancef936d2021-07-21 16:17:52 +00003213 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3214 REQUIRES(mLock) {
3215 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003216 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003217 };
3218 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219}
3220
3221void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003222 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003223 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003224 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003225 ATRACE_NAME_IF(ATRACE_ENABLED(),
3226 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3227 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003228 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003229 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003230 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003231 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003232 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003233 inputTarget.getPointerInfoString().c_str());
3234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235
3236 // Skip this event if the connection status is not normal.
3237 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003238 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003239 if (DEBUG_DISPATCH_CYCLE) {
3240 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003241 connection->getInputChannelName().c_str(),
3242 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 return;
3245 }
3246
3247 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003248 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003249 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003250 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003251 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003253 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003254 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003255 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3256 logDispatchStateLocked();
3257 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3258 "target on connection "
3259 << connection->getInputChannelName() << " for "
3260 << originalMotionEntry.getDescription();
3261 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003262 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003263 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3264 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 if (!splitMotionEntry) {
3266 return; // split event was dropped
3267 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003268 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3269 std::string reason = std::string("reason=pointer cancel on split window");
3270 android_log_event_list(LOGTAG_INPUT_CANCEL)
3271 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3272 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003273 if (DEBUG_FOCUS) {
3274 ALOGD("channel '%s' ~ Split motion event.",
3275 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003276 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003277 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003278 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3279 std::move(splitMotionEntry),
3280 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 return;
3282 }
3283 }
3284
3285 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003286 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3287 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288}
3289
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003290void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3291 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3292 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003293 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003294 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3295 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003296 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003297
hongzuo liu95785e22022-09-06 02:51:35 +00003298 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003300 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003303 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 startDispatchCycleLocked(currentTime, connection);
3305 }
3306}
3307
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003308void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003309 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003310 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 // This is a new event.
3312 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003313 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003314 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003316 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3317 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003318 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003320 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003321 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003322 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3323 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003324 LOG(WARNING) << "channel " << connection->getInputChannelName()
3325 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 return; // skip the inconsistent event
3327 }
3328 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003331 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003332 std::shared_ptr<const MotionEntry> resolvedMotion =
3333 std::static_pointer_cast<const MotionEntry>(eventEntry);
3334 {
3335 // Determine the resolved motion entry.
3336 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3337 int32_t resolvedAction = motionEntry.action;
3338 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003340 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003341 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003342 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003343 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003344 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003345 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003346 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003347 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003348 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003349 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3350 }
3351 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3352 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3353 motionEntry.displayId)) {
3354 if (DEBUG_DISPATCH_CYCLE) {
3355 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3356 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3357 "enter event";
3358 }
3359 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3360 }
3361
3362 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3363 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3364 }
3365 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3366 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3367 }
3368 if (dispatchEntry->targetFlags.test(
3369 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3370 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3371 }
3372
3373 dispatchEntry->resolvedFlags = resolvedFlags;
3374 if (resolvedAction != motionEntry.action) {
3375 // Generate a new MotionEntry with a new eventId using the resolved action and
3376 // flags.
3377 resolvedMotion =
3378 std::make_shared<MotionEntry>(mIdGenerator.nextId(),
3379 motionEntry.injectionState,
3380 motionEntry.eventTime,
3381 motionEntry.deviceId, motionEntry.source,
3382 motionEntry.displayId,
3383 motionEntry.policyFlags, resolvedAction,
3384 motionEntry.actionButton, resolvedFlags,
3385 motionEntry.metaState,
3386 motionEntry.buttonState,
3387 motionEntry.classification,
3388 motionEntry.edgeFlags,
3389 motionEntry.xPrecision,
3390 motionEntry.yPrecision,
3391 motionEntry.xCursorPosition,
3392 motionEntry.yCursorPosition,
3393 motionEntry.downTime,
3394 motionEntry.pointerProperties,
3395 motionEntry.pointerCoords);
3396 if (ATRACE_ENABLED()) {
3397 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3398 ") to MotionEvent(id=0x%" PRIx32 ").",
3399 motionEntry.id, resolvedMotion->id);
3400 ATRACE_NAME(message.c_str());
3401 }
3402
3403 // Set the resolved motion entry in the DispatchEntry.
3404 dispatchEntry->eventEntry = resolvedMotion;
3405 eventEntry = resolvedMotion;
3406 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003409 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3410 // devices being active at the same time in the same window, so if a new device is
3411 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003412 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003413 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003414 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003415 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003416 << connection->getInputChannelName() << " with event "
3417 << cancelEvent->getDescription();
3418 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3419 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003420 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003421
3422 // Send these cancel events to the queue before sending the event from the new
3423 // device.
3424 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3425 }
3426
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003427 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003429 LOG(WARNING) << "channel " << connection->getInputChannelName()
3430 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 return; // skip the inconsistent event
3432 }
3433
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003434 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3435 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003436 // Skip reporting pointer down outside focus to the policy.
3437 break;
3438 }
3439
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003440 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003441 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003442
3443 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003445 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003446 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003447 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3448 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003449 break;
3450 }
Chris Yef59a2f42020-10-16 12:55:26 -07003451 case EventEntry::Type::SENSOR: {
3452 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3453 break;
3454 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003455 case EventEntry::Type::CONFIGURATION_CHANGED:
3456 case EventEntry::Type::DEVICE_RESET: {
3457 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003458 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003459 break;
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462
3463 // Remember that we are waiting for this dispatch to complete.
3464 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003465 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 }
3467
3468 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003469 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003470 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003471}
3472
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003473/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003474 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003476 * The first role is to log input interaction with windows, which helps determine what the user was
3477 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3478 * that user started interacting with launcher window, as well as any other window that received
3479 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3480 * when the set of tokens that received the event changes. It is not logged again as long as the
3481 * user is interacting with the same windows.
3482 *
3483 * The second role is to track input device activity for metrics collection. For each input event,
3484 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3485 * input_interaction logs, the device interaction is reported even when the set of interaction
3486 * tokens do not change.
3487 *
3488 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3489 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003491void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3492 const std::vector<InputTarget>& targets) {
3493 int32_t deviceId;
3494 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003495 // Skip ACTION_UP events, and all events other than keys and motions
3496 if (entry.type == EventEntry::Type::KEY) {
3497 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3498 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3499 return;
3500 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003501 deviceId = keyEntry.deviceId;
3502 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003503 } else if (entry.type == EventEntry::Type::MOTION) {
3504 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3505 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003506 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3507 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003508 return;
3509 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003510 deviceId = motionEntry.deviceId;
3511 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003512 } else {
3513 return; // Not a key or a motion
3514 }
3515
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003516 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003517 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003518 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003519 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003520 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003521 continue; // Skip windows that receive ACTION_OUTSIDE
3522 }
3523
3524 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003525 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003526 if (connection == nullptr) {
3527 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003528 }
3529 newConnectionTokens.insert(std::move(token));
3530 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003531 if (target.windowHandle) {
3532 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3533 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003534 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003535
3536 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3537 REQUIRES(mLock) {
3538 scoped_unlock unlock(mLock);
3539 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3540 };
3541 postCommandLocked(std::move(command));
3542
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003543 if (newConnectionTokens == mInteractionConnectionTokens) {
3544 return; // no change
3545 }
3546 mInteractionConnectionTokens = newConnectionTokens;
3547
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003548 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003549 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003550 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003551 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003552 std::string message = "Interaction with: " + targetList;
3553 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003554 message += "<none>";
3555 }
3556 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3557}
3558
chaviwfd6d3512019-03-25 13:23:49 -07003559void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003560 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003561 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003562 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3563 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003564 return;
3565 }
3566
Vishnu Nairc519ff72021-01-21 08:23:08 -08003567 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003568 if (focusedToken == token) {
3569 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003570 return;
3571 }
3572
Prabir Pradhancef936d2021-07-21 16:17:52 +00003573 auto command = [this, token]() REQUIRES(mLock) {
3574 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003575 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003576 };
3577 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578}
3579
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003580status_t InputDispatcher::publishMotionEvent(Connection& connection,
3581 DispatchEntry& dispatchEntry) const {
3582 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3583 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3584
3585 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003586 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003587
3588 // Set the X and Y offset and X and Y scale depending on the input source.
3589 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003590 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003591 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3592 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003593 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003594 scaledCoords[i] = motionEntry.pointerCoords[i];
3595 // Don't apply window scale here since we don't want scale to affect raw
3596 // coordinates. The scale will be sent back to the client and applied
3597 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003598 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003599 }
3600 usingCoords = scaledCoords;
3601 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003602 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003603 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003604 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003605 scaledCoords[i].clear();
3606 }
3607 usingCoords = scaledCoords;
3608 }
3609
3610 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3611
3612 // Publish the motion event.
3613 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003614 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3615 motionEntry.source, motionEntry.displayId, std::move(hmac),
3616 motionEntry.action, motionEntry.actionButton,
3617 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3618 motionEntry.metaState, motionEntry.buttonState,
3619 motionEntry.classification, dispatchEntry.transform,
3620 motionEntry.xPrecision, motionEntry.yPrecision,
3621 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3622 dispatchEntry.rawTransform, motionEntry.downTime,
3623 motionEntry.eventTime, motionEntry.getPointerCount(),
3624 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003625}
3626
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003628 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003629 ATRACE_NAME_IF(ATRACE_ENABLED(),
3630 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3631 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003632 if (DEBUG_DISPATCH_CYCLE) {
3633 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003636 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003637 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003639 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003640 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641
3642 // Publish the event.
3643 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003644 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3645 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003646 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003647 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3648 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003649 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003650 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3651 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003654 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003655 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003656 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3657 keyEntry.deviceId, keyEntry.source,
3658 keyEntry.displayId, std::move(hmac),
3659 keyEntry.action, dispatchEntry->resolvedFlags,
3660 keyEntry.keyCode, keyEntry.scanCode,
3661 keyEntry.metaState, keyEntry.repeatCount,
3662 keyEntry.downTime, keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003663 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
3665
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003666 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003667 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003668 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3669 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003670 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003671 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003672 break;
3673 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003674
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003675 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003677 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003678 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003679 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003680 break;
3681 }
3682
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003683 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3684 const TouchModeEntry& touchModeEntry =
3685 static_cast<const TouchModeEntry&>(eventEntry);
3686 status = connection->inputPublisher
3687 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3688 touchModeEntry.inTouchMode);
3689
3690 break;
3691 }
3692
Prabir Pradhan99987712020-11-10 18:43:05 -08003693 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3694 const auto& captureEntry =
3695 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3696 status = connection->inputPublisher
3697 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003698 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003699 break;
3700 }
3701
arthurhungb89ccb02020-12-30 16:19:01 +08003702 case EventEntry::Type::DRAG: {
3703 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3704 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3705 dragEntry.id, dragEntry.x,
3706 dragEntry.y,
3707 dragEntry.isExiting);
3708 break;
3709 }
3710
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003711 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003712 case EventEntry::Type::DEVICE_RESET:
3713 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003714 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003715 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003716 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
3720 // Check the result.
3721 if (status) {
3722 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003723 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003725 "This is unexpected because the wait queue is empty, so the pipe "
3726 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003727 "event to it, status=%s(%d)",
3728 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3729 status);
Harry Cutts33476232023-01-30 19:57:29 +00003730 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 } else {
3732 // Pipe is full and we are waiting for the app to finish process some events
3733 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003734 if (DEBUG_DISPATCH_CYCLE) {
3735 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3736 "waiting for the application to catch up",
3737 connection->getInputChannelName().c_str());
3738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 }
3740 } else {
3741 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003742 "status=%s(%d)",
3743 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3744 status);
Harry Cutts33476232023-01-30 19:57:29 +00003745 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 }
3747 return;
3748 }
3749
3750 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003751 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3752 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3753 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003754 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003755 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003756 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003757 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003758 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 }
3760}
3761
chaviw09c8d2d2020-08-24 15:48:26 -07003762std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3763 size_t size;
3764 switch (event.type) {
3765 case VerifiedInputEvent::Type::KEY: {
3766 size = sizeof(VerifiedKeyEvent);
3767 break;
3768 }
3769 case VerifiedInputEvent::Type::MOTION: {
3770 size = sizeof(VerifiedMotionEvent);
3771 break;
3772 }
3773 }
3774 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3775 return mHmacKeyManager.sign(start, size);
3776}
3777
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003778const std::array<uint8_t, 32> InputDispatcher::getSignature(
3779 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003780 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003781 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003782 // Only sign events up and down events as the purely move events
3783 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003784 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003785 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003786
3787 VerifiedMotionEvent verifiedEvent =
3788 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3789 verifiedEvent.actionMasked = actionMasked;
3790 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3791 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003792}
3793
3794const std::array<uint8_t, 32> InputDispatcher::getSignature(
3795 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3796 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3797 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003798 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003799}
3800
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003802 const std::shared_ptr<Connection>& connection,
3803 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003804 if (DEBUG_DISPATCH_CYCLE) {
3805 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3806 connection->getInputChannelName().c_str(), seq, toString(handled));
3807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003809 if (connection->status == Connection::Status::BROKEN ||
3810 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 return;
3812 }
3813
3814 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003815 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3816 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3817 };
3818 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819}
3820
3821void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003822 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003823 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003824 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003825 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3826 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
3829 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003830 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003831 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003832 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003833 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834
3835 // The connection appears to be unrecoverably broken.
3836 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003837 if (connection->status == Connection::Status::NORMAL) {
3838 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839
3840 if (notify) {
3841 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003842 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3843 connection->getInputChannelName().c_str());
3844
3845 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003846 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003847 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003848 };
3849 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851 }
3852}
3853
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003854void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003855 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003856 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003857 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
3859}
3860
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003861void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003863 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865}
3866
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003867int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3868 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003869 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003870 if (connection == nullptr) {
3871 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3872 connectionToken.get(), events);
3873 return 0; // remove the callback
3874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003876 bool notify;
3877 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3878 if (!(events & ALOOPER_EVENT_INPUT)) {
3879 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3880 "events=0x%x",
3881 connection->getInputChannelName().c_str(), events);
3882 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 }
3884
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003885 nsecs_t currentTime = now();
3886 bool gotOne = false;
3887 status_t status = OK;
3888 for (;;) {
3889 Result<InputPublisher::ConsumerResponse> result =
3890 connection->inputPublisher.receiveConsumerResponse();
3891 if (!result.ok()) {
3892 status = result.error().code();
3893 break;
3894 }
3895
3896 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3897 const InputPublisher::Finished& finish =
3898 std::get<InputPublisher::Finished>(*result);
3899 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3900 finish.consumeTime);
3901 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003902 if (shouldReportMetricsForConnection(*connection)) {
3903 const InputPublisher::Timeline& timeline =
3904 std::get<InputPublisher::Timeline>(*result);
3905 mLatencyTracker
3906 .trackGraphicsLatency(timeline.inputEventId,
3907 connection->inputChannel->getConnectionToken(),
3908 std::move(timeline.graphicsTimeline));
3909 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003910 }
3911 gotOne = true;
3912 }
3913 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003914 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003915 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 return 1;
3917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 }
3919
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003920 notify = status != DEAD_OBJECT || !connection->monitor;
3921 if (notify) {
3922 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3923 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3924 status);
3925 }
3926 } else {
3927 // Monitor channels are never explicitly unregistered.
3928 // We do it automatically when the remote endpoint is closed so don't warn about them.
3929 const bool stillHaveWindowHandle =
3930 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3931 notify = !connection->monitor && stillHaveWindowHandle;
3932 if (notify) {
3933 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3934 connection->getInputChannelName().c_str(), events);
3935 }
3936 }
3937
3938 // Remove the channel.
3939 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3940 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941}
3942
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003943void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003945 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003946 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 }
3948}
3949
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003951 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003952 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003953 for (const Monitor& monitor : monitors) {
3954 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003955 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003956 }
3957}
3958
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003960 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003961 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003962 if (connection == nullptr) {
3963 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003965
3966 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967}
3968
3969void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003970 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003971 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 return;
3973 }
3974
3975 nsecs_t currentTime = now();
3976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003977 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003978 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980 if (cancelationEvents.empty()) {
3981 return;
3982 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00003983
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003984 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3985 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003986 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003987 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003988 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003989 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003990
Arthur Hungb3307ee2021-10-14 10:57:37 +00003991 std::string reason = std::string("reason=").append(options.reason);
3992 android_log_event_list(LOGTAG_INPUT_CANCEL)
3993 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3994
hongzuo liu95785e22022-09-06 02:51:35 +00003995 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003996 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003997 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00003998 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003999
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004000 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004001 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004002 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004003
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004004 switch (cancelationEventEntry->type) {
4005 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004006 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004007 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4008 ? std::make_optional(keyEntry.displayId)
4009 : std::nullopt;
4010 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004011 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4012 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004013 } else {
4014 targets.emplace_back(fallbackTarget);
4015 }
4016 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004017 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004019 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004020 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004021 const std::optional<int32_t> targetDisplay =
4022 motionEntry.displayId != ADISPLAY_ID_NONE
4023 ? std::make_optional(motionEntry.displayId)
4024 : std::nullopt;
4025 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004026 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004027 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004028 pointerIndex++) {
4029 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4030 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004031 if (mDragState && mDragState->dragWindow->getToken() == token &&
4032 pointerIds.test(mDragState->pointerId)) {
4033 LOG(INFO) << __func__
4034 << ": Canceling drag and drop because the pointers for the drag "
4035 "window are being canceled.";
4036 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4037 mDragState.reset();
4038 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004039 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4040 ftl::Flags<InputTarget::Flags>(), pointerIds,
4041 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004042 } else {
4043 targets.emplace_back(fallbackTarget);
4044 const auto it = mDisplayInfos.find(motionEntry.displayId);
4045 if (it != mDisplayInfos.end()) {
4046 targets.back().displayTransform = it->second.transform;
4047 targets.back().setDefaultPointerTransform(it->second.transform);
4048 }
4049 }
4050 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004053 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004054 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004055 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4056 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004057 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004058 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004059 break;
4060 }
4061 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004062 case EventEntry::Type::DEVICE_RESET:
4063 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004064 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004065 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004066 break;
4067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 }
4069
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004070 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004071 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
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 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004114 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4115 targetFlags, pointerIds, motionEntry.downTime,
4116 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004117 } else {
4118 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4119 .flags = targetFlags});
4120 const auto it = mDisplayInfos.find(motionEntry.displayId);
4121 if (it != mDisplayInfos.end()) {
4122 targets.back().displayTransform = it->second.transform;
4123 targets.back().setDefaultPointerTransform(it->second.transform);
4124 }
4125 }
4126 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004127 break;
4128 }
4129
4130 case EventEntry::Type::KEY:
4131 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004132 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004133 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004134 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004135 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004136 case EventEntry::Type::SENSOR:
4137 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004138 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004139 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004140 break;
4141 }
4142 }
4143
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004144 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004145 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
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) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004550 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004551 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4552 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
Antonio Kantekf16f2832021-09-28 04:39:20 +00004555 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004557 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004559 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004560 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004561 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004562
4563 for (auto& [_, verifier] : mVerifiersByDisplay) {
4564 verifier.resetDevice(args.deviceId);
4565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 } // release lock
4567
4568 if (needWake) {
4569 mLooper->wake();
4570 }
4571}
4572
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004573void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004574 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004575 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4576 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004577 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004578
Antonio Kantekf16f2832021-09-28 04:39:20 +00004579 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004580 { // acquire lock
4581 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004582 auto entry =
4583 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004584 needWake = enqueueInboundEventLocked(std::move(entry));
4585 } // release lock
4586
4587 if (needWake) {
4588 mLooper->wake();
4589 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004590}
4591
Prabir Pradhan5735a322022-04-11 17:23:34 +00004592InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004593 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004594 InputEventInjectionSync syncMode,
4595 std::chrono::milliseconds timeout,
4596 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004597 Result<void> eventValidation = validateInputEvent(*event);
4598 if (!eventValidation.ok()) {
4599 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4600 return InputEventInjectionResult::FAILED;
4601 }
4602
Prabir Pradhan65613802023-02-22 23:36:58 +00004603 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004604 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4605 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4606 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4607 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004608 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004609 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Prabir Pradhan5735a322022-04-11 17:23:34 +00004611 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004613 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004614 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4615 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4616 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4617 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4618 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004619 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004620 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004621 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004622 }
4623
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004624 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4625 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4626
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004627 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004629 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004630 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004631 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004632 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004633 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4634 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4635 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004636 int32_t keyCode = incomingKey.getKeyCode();
4637 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004638 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004639 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004640 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4641 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4642 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004644 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4645 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004646 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004647
4648 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4649 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004650 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004651 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4652 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4653 std::to_string(t.duration().count()).c_str());
4654 }
4655 }
4656
4657 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004659 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4660 incomingKey.getEventTime(), resolvedDeviceId,
4661 incomingKey.getSource(), incomingKey.getDisplayId(),
4662 policyFlags, action, flags, keyCode,
4663 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004664 incomingKey.getRepeatCount(),
4665 incomingKey.getDownTime());
4666 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004667 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 }
4669
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004670 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004671 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004672 const bool isPointerEvent =
4673 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4674 // If a pointer event has no displayId specified, inject it to the default display.
4675 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4676 ? ADISPLAY_ID_DEFAULT
4677 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004678 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679
4680 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004681 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004682 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004683 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4685 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4686 std::to_string(t.duration().count()).c_str());
4687 }
4688 }
4689
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004690 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4691 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4692 }
4693
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004694 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004695 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004696 const size_t pointerCount = motionEvent.getPointerCount();
4697 const std::vector<PointerProperties>
4698 pointerProperties(motionEvent.getPointerProperties(),
4699 motionEvent.getPointerProperties() + pointerCount);
4700
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004701 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004702 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004703 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4704 *sampleEventTimes, resolvedDeviceId,
4705 motionEvent.getSource(), displayId, policyFlags,
4706 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004707 motionEvent.getActionButton(), flags,
4708 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004709 motionEvent.getButtonState(),
4710 motionEvent.getClassification(),
4711 motionEvent.getEdgeFlags(),
4712 motionEvent.getXPrecision(),
4713 motionEvent.getYPrecision(),
4714 motionEvent.getRawXCursorPosition(),
4715 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004716 motionEvent.getDownTime(), pointerProperties,
4717 std::vector<PointerCoords>(samplePointerCoords,
4718 samplePointerCoords +
4719 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004720 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004721 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004722 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004724 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004725 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004726 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4727 resolvedDeviceId, motionEvent.getSource(), displayId,
4728 policyFlags, motionEvent.getAction(),
4729 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004730 motionEvent.getMetaState(), motionEvent.getButtonState(),
4731 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4732 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4733 motionEvent.getRawXCursorPosition(),
4734 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4735 pointerProperties,
4736 std::vector<PointerCoords>(samplePointerCoords,
4737 samplePointerCoords +
4738 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004739 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4740 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004741 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 }
4743 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004747 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004748 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 }
4750
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004752 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004753 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004754 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004755 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004756 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004757 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 }
4759
4760 mLock.unlock();
4761
4762 if (needWake) {
4763 mLooper->wake();
4764 }
4765
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004766 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004768 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004770 if (syncMode == InputEventInjectionSync::NONE) {
4771 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 } else {
4773 for (;;) {
4774 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004775 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 break;
4777 }
4778
4779 nsecs_t remainingTimeout = endTime - now();
4780 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004781 if (DEBUG_INJECTION) {
4782 ALOGD("injectInputEvent - Timed out waiting for injection result "
4783 "to become available.");
4784 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004785 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 break;
4787 }
4788
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004789 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 }
4791
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004792 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4793 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004795 if (DEBUG_INJECTION) {
4796 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4797 injectionState->pendingForegroundDispatches);
4798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 nsecs_t remainingTimeout = endTime - now();
4800 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004801 if (DEBUG_INJECTION) {
4802 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4803 "dispatches to finish.");
4804 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 break;
4807 }
4808
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004809 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 }
4811 }
4812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 } // release lock
4814
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004815 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004816 LOG(INFO) << "injectInputEvent - Finished with result "
4817 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
4820 return injectionResult;
4821}
4822
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004823std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004824 std::array<uint8_t, 32> calculatedHmac;
4825 std::unique_ptr<VerifiedInputEvent> result;
4826 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004827 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004828 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4829 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4830 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004831 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004832 break;
4833 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004834 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004835 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4836 VerifiedMotionEvent verifiedMotionEvent =
4837 verifiedMotionEventFromMotionEvent(motionEvent);
4838 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004839 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004840 break;
4841 }
4842 default: {
4843 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4844 return nullptr;
4845 }
4846 }
4847 if (calculatedHmac == INVALID_HMAC) {
4848 return nullptr;
4849 }
tyiu1573a672023-02-21 22:38:32 +00004850 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004851 return nullptr;
4852 }
4853 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004854}
4855
Prabir Pradhan24047542023-11-02 17:14:59 +00004856void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004857 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004858 if (!entry.injectionState) {
4859 // Not an injected event.
4860 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004862
4863 InjectionState& injectionState = *entry.injectionState;
4864 if (DEBUG_INJECTION) {
4865 LOG(INFO) << "Setting input event injection result to "
4866 << ftl::enum_string(injectionResult);
4867 }
4868
4869 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4870 // Log the outcome since the injector did not wait for the injection result.
4871 switch (injectionResult) {
4872 case InputEventInjectionResult::SUCCEEDED:
4873 ALOGV("Asynchronous input event injection succeeded.");
4874 break;
4875 case InputEventInjectionResult::TARGET_MISMATCH:
4876 ALOGV("Asynchronous input event injection target mismatch.");
4877 break;
4878 case InputEventInjectionResult::FAILED:
4879 ALOGW("Asynchronous input event injection failed.");
4880 break;
4881 case InputEventInjectionResult::TIMED_OUT:
4882 ALOGW("Asynchronous input event injection timed out.");
4883 break;
4884 case InputEventInjectionResult::PENDING:
4885 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4886 break;
4887 }
4888 }
4889
4890 injectionState.injectionResult = injectionResult;
4891 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892}
4893
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004894void InputDispatcher::transformMotionEntryForInjectionLocked(
4895 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004896 // Input injection works in the logical display coordinate space, but the input pipeline works
4897 // display space, so we need to transform the injected events accordingly.
4898 const auto it = mDisplayInfos.find(entry.displayId);
4899 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004900 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004901
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004902 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4903 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4904 const vec2 cursor =
4905 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4906 {entry.xCursorPosition, entry.yCursorPosition});
4907 entry.xCursorPosition = cursor.x;
4908 entry.yCursorPosition = cursor.y;
4909 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004910 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004911 entry.pointerCoords[i] =
4912 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4913 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004914 }
4915}
4916
Prabir Pradhan24047542023-11-02 17:14:59 +00004917void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004918 if (entry.injectionState) {
4919 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 }
4921}
4922
Prabir Pradhan24047542023-11-02 17:14:59 +00004923void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004924 if (entry.injectionState) {
4925 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004927 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004928 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
4930 }
4931}
4932
chaviw98318de2021-05-19 16:45:23 -05004933const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004934 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004935 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004936 auto it = mWindowHandlesByDisplay.find(displayId);
4937 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004938}
4939
chaviw98318de2021-05-19 16:45:23 -05004940sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004941 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004942 if (windowHandleToken == nullptr) {
4943 return nullptr;
4944 }
4945
Prabir Pradhan16463382023-10-12 23:03:19 +00004946 if (!displayId) {
4947 // Look through all displays.
4948 for (auto& it : mWindowHandlesByDisplay) {
4949 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4950 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4951 if (windowHandle->getToken() == windowHandleToken) {
4952 return windowHandle;
4953 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004956 return nullptr;
4957 }
4958
Prabir Pradhan16463382023-10-12 23:03:19 +00004959 // Only look through the requested display.
4960 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004961 if (windowHandle->getToken() == windowHandleToken) {
4962 return windowHandle;
4963 }
4964 }
4965 return nullptr;
4966}
4967
chaviw98318de2021-05-19 16:45:23 -05004968sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4969 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004970 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004971 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4972 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004973 if (handle->getId() == windowHandle->getId() &&
4974 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004975 if (windowHandle->getInfo()->displayId != it.first) {
4976 ALOGE("Found window %s in display %" PRId32
4977 ", but it should belong to display %" PRId32,
4978 windowHandle->getName().c_str(), it.first,
4979 windowHandle->getInfo()->displayId);
4980 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004981 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983 }
4984 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004985 return nullptr;
4986}
4987
chaviw98318de2021-05-19 16:45:23 -05004988sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004989 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4990 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991}
4992
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004993ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4994 auto displayInfoIt = mDisplayInfos.find(displayId);
4995 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4996 : kIdentityTransform;
4997}
4998
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004999bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5000 const MotionEntry& motionEntry) const {
5001 const WindowInfo& info = *window->getInfo();
5002
5003 // Skip spy window targets that are not valid for targeted injection.
5004 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005005 return false;
5006 }
5007
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005008 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5009 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5010 return false;
5011 }
5012
5013 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5014 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5015 window->getName().c_str());
5016 return false;
5017 }
5018
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005019 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005020 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005021 ALOGW("Not sending touch to %s because there's no corresponding connection",
5022 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005023 return false;
5024 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005025
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005026 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005027 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005028 return false;
5029 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005030
5031 // Drop events that can't be trusted due to occlusion
5032 const auto [x, y] = resolveTouchedPosition(motionEntry);
5033 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5034 if (!isTouchTrustedLocked(occlusionInfo)) {
5035 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005036 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005037 for (const auto& log : occlusionInfo.debugInfo) {
5038 ALOGD("%s", log.c_str());
5039 }
5040 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005041 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5042 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005043 return false;
5044 }
5045
5046 // Drop touch events if requested by input feature
5047 if (shouldDropInput(motionEntry, window)) {
5048 return false;
5049 }
5050
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005051 return true;
5052}
5053
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005054std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5055 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005056 auto connectionIt = mConnectionsByToken.find(token);
5057 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005058 return nullptr;
5059 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005060 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005061}
5062
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005063void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005064 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5065 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005066 // Remove all handles on a display if there are no windows left.
5067 mWindowHandlesByDisplay.erase(displayId);
5068 return;
5069 }
5070
5071 // Since we compare the pointer of input window handles across window updates, we need
5072 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005073 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5074 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5075 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005076 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005077 }
5078
chaviw98318de2021-05-19 16:45:23 -05005079 std::vector<sp<WindowInfoHandle>> newHandles;
5080 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005081 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005082 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005083 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005084 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005085 const bool canReceiveInput =
5086 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5087 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005088 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005089 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005090 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005091 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005092 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005093 }
5094
5095 if (info->displayId != displayId) {
5096 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5097 handle->getName().c_str(), displayId, info->displayId);
5098 continue;
5099 }
5100
Robert Carredd13602020-04-13 17:24:34 -07005101 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5102 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005103 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005104 oldHandle->updateFrom(handle);
5105 newHandles.push_back(oldHandle);
5106 } else {
5107 newHandles.push_back(handle);
5108 }
5109 }
5110
5111 // Insert or replace
5112 mWindowHandlesByDisplay[displayId] = newHandles;
5113}
5114
Arthur Hungb92218b2018-08-14 12:00:21 +08005115/**
5116 * Called from InputManagerService, update window handle list by displayId that can receive input.
5117 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5118 * If set an empty list, remove all handles from the specific display.
5119 * For focused handle, check if need to change and send a cancel event to previous one.
5120 * For removed handle, check if need to send a cancel event if already in touch.
5121 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005122void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005123 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005124 if (DEBUG_FOCUS) {
5125 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005126 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005127 windowList += iwh->getName() + " ";
5128 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005129 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Prabir Pradhand65552b2021-10-07 11:23:50 -07005132 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005133 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005134 const WindowInfo& info = *window->getInfo();
5135
5136 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005137 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005138 if (noInputWindow && window->getToken() != nullptr) {
5139 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5140 window->getName().c_str());
5141 window->releaseChannel();
5142 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005143
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005144 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005145 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5146 !info.inputConfig.test(
5147 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005148 "%s has feature SPY, but is not a trusted overlay.",
5149 window->getName().c_str());
5150
Prabir Pradhand65552b2021-10-07 11:23:50 -07005151 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005152 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5153 !info.inputConfig.test(
5154 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005155 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5156 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005157 }
5158
Arthur Hung72d8dc32020-03-28 00:48:39 +00005159 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005160 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161
chaviw98318de2021-05-19 16:45:23 -05005162 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005163
chaviw98318de2021-05-19 16:45:23 -05005164 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005165
Vishnu Nairc519ff72021-01-21 08:23:08 -08005166 std::optional<FocusResolver::FocusChanges> changes =
5167 mFocusResolver.setInputWindows(displayId, windowHandles);
5168 if (changes) {
5169 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005172 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5173 mTouchStatesByDisplay.find(displayId);
5174 if (stateIt != mTouchStatesByDisplay.end()) {
5175 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005176 for (size_t i = 0; i < state.windows.size();) {
5177 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005178 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005179 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5180 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005181 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005182 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5183 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005184 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005185 "touched window was removed");
5186 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005187 // Since we are about to drop the touch, cancel the events for the wallpaper as
5188 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005189 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005190 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5191 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005192 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005193 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005196 state.windows.erase(state.windows.begin() + i);
5197 } else {
5198 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199 }
5200 }
arthurhungb89ccb02020-12-30 16:19:01 +08005201
arthurhung6d4bed92021-03-17 11:59:33 +08005202 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005203 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005204 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005205 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005206 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005207 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5208 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005209 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005210 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005211 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005212
Arthur Hung72d8dc32020-03-28 00:48:39 +00005213 // Release information for windows that are no longer present.
5214 // This ensures that unused input channels are released promptly.
5215 // Otherwise, they might stick around until the window handle is destroyed
5216 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005217 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005218 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005219 if (DEBUG_FOCUS) {
5220 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005221 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005222 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005223 }
chaviw291d88a2019-02-14 10:33:58 -08005224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225}
5226
5227void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005228 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005229 if (DEBUG_FOCUS) {
5230 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5231 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5232 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005233 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005234 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005235 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 } // release lock
5237
5238 // Wake up poll loop since it may need to make new input dispatching choices.
5239 mLooper->wake();
5240}
5241
Vishnu Nair599f1412021-06-21 10:39:58 -07005242void InputDispatcher::setFocusedApplicationLocked(
5243 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5244 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5245 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5246
5247 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5248 return; // This application is already focused. No need to wake up or change anything.
5249 }
5250
5251 // Set the new application handle.
5252 if (inputApplicationHandle != nullptr) {
5253 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5254 } else {
5255 mFocusedApplicationHandlesByDisplay.erase(displayId);
5256 }
5257
5258 // No matter what the old focused application was, stop waiting on it because it is
5259 // no longer focused.
5260 resetNoFocusedWindowTimeoutLocked();
5261}
5262
Tiger Huang721e26f2018-07-24 22:26:19 +08005263/**
5264 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5265 * the display not specified.
5266 *
5267 * We track any unreleased events for each window. If a window loses the ability to receive the
5268 * released event, we will send a cancel event to it. So when the focused display is changed, we
5269 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5270 * display. The display-specified events won't be affected.
5271 */
5272void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005273 if (DEBUG_FOCUS) {
5274 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5275 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005276 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005277 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005278
5279 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005280 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005281 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005282 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005283 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005284 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005285 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005286 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005287 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005288 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005289 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005290 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5291 }
5292 }
5293 mFocusedDisplayId = displayId;
5294
Chris Ye3c2d6f52020-08-09 10:39:48 -07005295 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005296 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005297 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005298
Vishnu Nairad321cd2020-08-20 16:40:21 -07005299 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005300 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005301 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005302 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005303 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005304 }
5305 }
5306 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005307 } // release lock
5308
5309 // Wake up poll loop since it may need to make new input dispatching choices.
5310 mLooper->wake();
5311}
5312
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005314 if (DEBUG_FOCUS) {
5315 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317
5318 bool changed;
5319 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005320 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321
5322 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5323 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005324 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
5326
5327 if (mDispatchEnabled && !enabled) {
5328 resetAndDropEverythingLocked("dispatcher is being disabled");
5329 }
5330
5331 mDispatchEnabled = enabled;
5332 mDispatchFrozen = frozen;
5333 changed = true;
5334 } else {
5335 changed = false;
5336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 } // release lock
5338
5339 if (changed) {
5340 // Wake up poll loop since it may need to make new input dispatching choices.
5341 mLooper->wake();
5342 }
5343}
5344
5345void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005346 if (DEBUG_FOCUS) {
5347 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349
5350 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005351 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352
5353 if (mInputFilterEnabled == enabled) {
5354 return;
5355 }
5356
5357 mInputFilterEnabled = enabled;
5358 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5359 } // release lock
5360
5361 // Wake up poll loop since there might be work to do to drop everything.
5362 mLooper->wake();
5363}
5364
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005365bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005366 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005367 bool needWake = false;
5368 {
5369 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005370 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005371 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005372 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005373 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5374 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005375 mTouchModePerDisplay.count(displayId) == 0
5376 ? "not set"
5377 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5378
Antonio Kantek15beb512022-06-13 22:35:41 +00005379 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5380 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005381 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005382 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005383 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005384 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5385 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005386 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005387 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005388 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005389 return false;
5390 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005391 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005392 mTouchModePerDisplay[displayId] = inTouchMode;
5393 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5394 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005395 needWake = enqueueInboundEventLocked(std::move(entry));
5396 } // release lock
5397
5398 if (needWake) {
5399 mLooper->wake();
5400 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005401 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005402}
5403
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005404bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005405 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5406 if (focusedToken == nullptr) {
5407 return false;
5408 }
5409 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5410 return isWindowOwnedBy(windowHandle, pid, uid);
5411}
5412
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005413bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005414 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5415 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5416 const sp<WindowInfoHandle> windowHandle =
5417 getWindowHandleLocked(connectionToken);
5418 return isWindowOwnedBy(windowHandle, pid, uid);
5419 }) != mInteractionConnectionTokens.end();
5420}
5421
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005422void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5423 if (opacity < 0 || opacity > 1) {
5424 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5425 return;
5426 }
5427
5428 std::scoped_lock lock(mLock);
5429 mMaximumObscuringOpacityForTouch = opacity;
5430}
5431
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005432std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5433InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005434 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5435 for (TouchedWindow& w : state.windows) {
5436 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005437 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005438 }
5439 }
5440 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005441 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005442}
5443
arthurhungb89ccb02020-12-30 16:19:01 +08005444bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5445 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005446 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005447 if (DEBUG_FOCUS) {
5448 ALOGD("Trivial transfer to same window.");
5449 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005450 return true;
5451 }
5452
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005454 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Arthur Hungabbb9d82021-09-01 14:52:30 +00005456 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005457 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005458
Arthur Hungabbb9d82021-09-01 14:52:30 +00005459 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005460 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 return false;
5462 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005463 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5464 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005465 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5466 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005467 return false;
5468 }
5469 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005470
Arthur Hungabbb9d82021-09-01 14:52:30 +00005471 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5472 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005473 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005474 return false;
5475 }
5476
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005477 if (DEBUG_FOCUS) {
5478 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005479 touchedWindow->windowHandle->getName().c_str(),
5480 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 }
5482
Arthur Hungabbb9d82021-09-01 14:52:30 +00005483 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005484 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005485 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005486 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005487 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
Arthur Hungabbb9d82021-09-01 14:52:30 +00005489 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005490 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005491 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005492 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005493 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005494 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005495 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005496 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
5497 deviceId, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498
Arthur Hungabbb9d82021-09-01 14:52:30 +00005499 // Store the dragging window.
5500 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005501 if (pointerIds.count() != 1) {
5502 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5503 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005504 return false;
5505 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005506 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005507 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005508 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509 }
5510
Arthur Hungabbb9d82021-09-01 14:52:30 +00005511 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005512 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5513 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005514 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005515 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005516 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5517 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005519 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5520 newTargetFlags);
5521
5522 // Check if the wallpaper window should deliver the corresponding event.
5523 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005524 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 } // release lock
5527
5528 // Wake up poll loop since it may need to make new input dispatching choices.
5529 mLooper->wake();
5530 return true;
5531}
5532
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005533/**
5534 * Get the touched foreground window on the given display.
5535 * Return null if there are no windows touched on that display, or if more than one foreground
5536 * window is being touched.
5537 */
5538sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5539 auto stateIt = mTouchStatesByDisplay.find(displayId);
5540 if (stateIt == mTouchStatesByDisplay.end()) {
5541 ALOGI("No touch state on display %" PRId32, displayId);
5542 return nullptr;
5543 }
5544
5545 const TouchState& state = stateIt->second;
5546 sp<WindowInfoHandle> touchedForegroundWindow;
5547 // If multiple foreground windows are touched, return nullptr
5548 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005549 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005550 if (touchedForegroundWindow != nullptr) {
5551 ALOGI("Two or more foreground windows: %s and %s",
5552 touchedForegroundWindow->getName().c_str(),
5553 window.windowHandle->getName().c_str());
5554 return nullptr;
5555 }
5556 touchedForegroundWindow = window.windowHandle;
5557 }
5558 }
5559 return touchedForegroundWindow;
5560}
5561
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005562// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005563bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005564 sp<IBinder> fromToken;
5565 { // acquire lock
5566 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005567 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005568 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005569 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5570 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005571 return false;
5572 }
5573
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005574 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5575 if (from == nullptr) {
5576 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5577 return false;
5578 }
5579
5580 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005581 } // release lock
5582
5583 return transferTouchFocus(fromToken, destChannelToken);
5584}
5585
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005587 if (DEBUG_FOCUS) {
5588 ALOGD("Resetting and dropping all events (%s).", reason);
5589 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590
Michael Wrightfb04fd52022-11-24 22:31:11 +00005591 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592 synthesizeCancelationEventsForAllConnectionsLocked(options);
5593
5594 resetKeyRepeatLocked();
5595 releasePendingEventLocked();
5596 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005597 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005599 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005600 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601}
5602
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005603void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005604 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 dumpDispatchStateLocked(dump);
5606
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005607 std::istringstream stream(dump);
5608 std::string line;
5609
5610 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005611 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
5613}
5614
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005615std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005616 std::string dump;
5617
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005618 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5619 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005620
5621 std::string windowName = "None";
5622 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005623 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005624 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5625 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5626 : "token has capture without window";
5627 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005628 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005629
5630 return dump;
5631}
5632
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005633void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005634 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5635 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5636 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005637 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638
Tiger Huang721e26f2018-07-24 22:26:19 +08005639 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5640 dump += StringPrintf(INDENT "FocusedApplications:\n");
5641 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5642 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005643 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005644 const std::chrono::duration timeout =
5645 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005646 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005647 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005648 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005651 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005653
Vishnu Nairc519ff72021-01-21 08:23:08 -08005654 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005655 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005657 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005658 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005659 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005660 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5661 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662 }
5663 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005664 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 }
5666
arthurhung6d4bed92021-03-17 11:59:33 +08005667 if (mDragState) {
5668 dump += StringPrintf(INDENT "DragState:\n");
5669 mDragState->dump(dump, INDENT2);
5670 }
5671
Arthur Hungb92218b2018-08-14 12:00:21 +08005672 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005673 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5674 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5675 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5676 const auto& displayInfo = it->second;
5677 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5678 displayInfo.logicalHeight);
5679 displayInfo.transform.dump(dump, "transform", INDENT4);
5680 } else {
5681 dump += INDENT2 "No DisplayInfo found!\n";
5682 }
5683
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005684 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005685 dump += INDENT2 "Windows:\n";
5686 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005687 dump += StringPrintf(INDENT3 "%zu: %s", i,
5688 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005689 }
5690 } else {
5691 dump += INDENT2 "Windows: <none>\n";
5692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 }
5694 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005695 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 }
5697
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005698 if (!mGlobalMonitorsByDisplay.empty()) {
5699 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5700 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005701 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005704 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
5706
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005707 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708
5709 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005710 if (!mRecentQueue.empty()) {
5711 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005712 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005713 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005714 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005715 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
5717 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005718 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719 }
5720
5721 // Dump event currently being dispatched.
5722 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005723 dump += INDENT "PendingEvent:\n";
5724 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005725 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005726 dump += StringPrintf(", age=%" PRId64 "ms\n",
5727 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005729 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
5731
5732 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005733 if (!mInboundQueue.empty()) {
5734 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005735 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005736 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005737 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005738 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 }
5740 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005741 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 }
5743
Prabir Pradhancef936d2021-07-21 16:17:52 +00005744 if (!mCommandQueue.empty()) {
5745 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5746 } else {
5747 dump += INDENT "CommandQueue: <empty>\n";
5748 }
5749
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005750 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005751 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005752 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005753 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005754 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005755 connection->inputChannel->getFd().get(),
5756 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005757 connection->getWindowName().c_str(),
5758 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005759 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005761 if (!connection->outboundQueue.empty()) {
5762 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5763 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005764 dump += dumpQueue(connection->outboundQueue, currentTime);
5765
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005767 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 }
5769
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005770 if (!connection->waitQueue.empty()) {
5771 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5772 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005773 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005777 std::string inputStateDump = streamableToString(connection->inputState);
5778 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005779 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005780 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 }
5783 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005784 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005787 dump += "input_flags::remove_app_switch_drops() = ";
Siarhei Vishniakou17f12282023-11-02 13:40:29 -07005788 dump += toString(REMOVE_APP_SWITCH_DROPS);
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07005789 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005791 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5792 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005794 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
Antonio Kantek15beb512022-06-13 22:35:41 +00005797 if (!mTouchModePerDisplay.empty()) {
5798 dump += INDENT "TouchModePerDisplay:\n";
5799 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5800 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5801 std::to_string(touchMode).c_str());
5802 }
5803 } else {
5804 dump += INDENT "TouchModePerDisplay: <none>\n";
5805 }
5806
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005807 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005808 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5809 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5810 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005811 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005812 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813}
5814
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005815void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005816 const size_t numMonitors = monitors.size();
5817 for (size_t i = 0; i < numMonitors; i++) {
5818 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005819 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005820 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5821 dump += "\n";
5822 }
5823}
5824
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005825class LooperEventCallback : public LooperCallback {
5826public:
5827 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5828 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5829
5830private:
5831 std::function<int(int events)> mCallback;
5832};
5833
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005834Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005835 if (DEBUG_CHANNEL_CREATION) {
5836 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005840 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005841 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005842
5843 if (result) {
5844 return base::Error(result) << "Failed to open input channel pair with name " << name;
5845 }
5846
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005848 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005849 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005850 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005851 std::shared_ptr<Connection> connection =
5852 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5853 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005855 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5856 ALOGE("Created a new connection, but the token %p is already known", token.get());
5857 }
5858 mConnectionsByToken.emplace(token, connection);
5859
5860 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5861 this, std::placeholders::_1, token);
5862
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005863 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005864 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865 } // release lock
5866
5867 // Wake the looper because some connections have changed.
5868 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005869 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870}
5871
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005872Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005873 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005874 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005875 std::shared_ptr<InputChannel> serverChannel;
5876 std::unique_ptr<InputChannel> clientChannel;
5877 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5878 if (result) {
5879 return base::Error(result) << "Failed to open input channel pair with name " << name;
5880 }
5881
Michael Wright3dd60e22019-03-27 22:06:44 +00005882 { // acquire lock
5883 std::scoped_lock _l(mLock);
5884
5885 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005886 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5887 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005888 }
5889
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005890 std::shared_ptr<Connection> connection =
5891 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005892 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005893 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005894
5895 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5896 ALOGE("Created a new connection, but the token %p is already known", token.get());
5897 }
5898 mConnectionsByToken.emplace(token, connection);
5899 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5900 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005901
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005902 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005903
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005904 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005905 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005906 }
Garfield Tan15601662020-09-22 15:32:38 -07005907
Michael Wright3dd60e22019-03-27 22:06:44 +00005908 // Wake the looper because some connections have changed.
5909 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005910 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005911}
5912
Garfield Tan15601662020-09-22 15:32:38 -07005913status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005915 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916
Harry Cutts33476232023-01-30 19:57:29 +00005917 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 if (status) {
5919 return status;
5920 }
5921 } // release lock
5922
5923 // Wake the poll loop because removing the connection may have changed the current
5924 // synchronization state.
5925 mLooper->wake();
5926 return OK;
5927}
5928
Garfield Tan15601662020-09-22 15:32:38 -07005929status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5930 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005931 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005932 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005933 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 return BAD_VALUE;
5935 }
5936
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005937 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005938
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005940 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 }
5942
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005943 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944
5945 nsecs_t currentTime = now();
5946 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5947
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005948 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 return OK;
5950}
5951
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005952void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005953 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5954 auto& [displayId, monitors] = *it;
5955 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5956 return monitor.inputChannel->getConnectionToken() == connectionToken;
5957 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005958
Michael Wright3dd60e22019-03-27 22:06:44 +00005959 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005960 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005961 } else {
5962 ++it;
5963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 }
5965}
5966
Michael Wright3dd60e22019-03-27 22:06:44 +00005967status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005968 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005969 return pilferPointersLocked(token);
5970}
Michael Wright3dd60e22019-03-27 22:06:44 +00005971
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005972status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005973 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5974 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005975 LOG(WARNING)
5976 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005977 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005978 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005979
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005980 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005981 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005982 LOG(WARNING)
5983 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5984 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005985 return BAD_VALUE;
5986 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005987 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005988 if (deviceIds.empty()) {
5989 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005990 return BAD_VALUE;
5991 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005992
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005993 for (const DeviceId deviceId : deviceIds) {
5994 TouchState& state = *statePtr;
5995 TouchedWindow& window = *windowPtr;
5996 // Send cancel events to all the input channels we're stealing from.
5997 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5998 "input channel stole pointer stream");
5999 options.deviceId = deviceId;
6000 options.displayId = displayId;
6001 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6002 options.pointerIds = pointerIds;
6003 std::string canceledWindows;
6004 for (const TouchedWindow& w : state.windows) {
6005 const std::shared_ptr<InputChannel> channel =
6006 getInputChannelLocked(w.windowHandle->getToken());
6007 if (channel != nullptr && channel->getConnectionToken() != token) {
6008 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6009 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6010 canceledWindows += channel->getName();
6011 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006012 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006013 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6014 LOG(INFO) << "Channel " << requestingChannel->getName()
6015 << " is stealing input gesture for device " << deviceId << " from "
6016 << canceledWindows;
6017
6018 // Prevent the gesture from being sent to any other windows.
6019 // This only blocks relevant pointers to be sent to other windows
6020 window.addPilferingPointers(deviceId, pointerIds);
6021
6022 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006023 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006024 return OK;
6025}
6026
Prabir Pradhan99987712020-11-10 18:43:05 -08006027void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6028 { // acquire lock
6029 std::scoped_lock _l(mLock);
6030 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006031 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006032 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6033 windowHandle != nullptr ? windowHandle->getName().c_str()
6034 : "token without window");
6035 }
6036
Vishnu Nairc519ff72021-01-21 08:23:08 -08006037 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006038 if (focusedToken != windowToken) {
6039 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6040 enabled ? "enable" : "disable");
6041 return;
6042 }
6043
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006044 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006045 ALOGW("Ignoring request to %s Pointer Capture: "
6046 "window has %s requested pointer capture.",
6047 enabled ? "enable" : "disable", enabled ? "already" : "not");
6048 return;
6049 }
6050
Christine Franksb768bb42021-11-29 12:11:31 -08006051 if (enabled) {
6052 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6053 mIneligibleDisplaysForPointerCapture.end(),
6054 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6055 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6056 return;
6057 }
6058 }
6059
Prabir Pradhan99987712020-11-10 18:43:05 -08006060 setPointerCaptureLocked(enabled);
6061 } // release lock
6062
6063 // Wake the thread to process command entries.
6064 mLooper->wake();
6065}
6066
Christine Franksb768bb42021-11-29 12:11:31 -08006067void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6068 { // acquire lock
6069 std::scoped_lock _l(mLock);
6070 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6071 if (!isEligible) {
6072 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6073 }
6074 } // release lock
6075}
6076
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006077std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006078 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006079 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006080 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006081 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006082 }
6083 }
6084 }
6085 return std::nullopt;
6086}
6087
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006088std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6089 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006090 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006091 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006092 }
6093
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006094 for (const auto& [token, connection] : mConnectionsByToken) {
6095 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006096 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 }
6098 }
Robert Carr4e670e52018-08-15 13:26:12 -07006099
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006100 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101}
6102
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006103std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006104 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006105 if (connection == nullptr) {
6106 return "<nullptr>";
6107 }
6108 return connection->getInputChannelName();
6109}
6110
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006111void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006112 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006113 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006114}
6115
Prabir Pradhancef936d2021-07-21 16:17:52 +00006116void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006117 const std::shared_ptr<Connection>& connection,
6118 uint32_t seq, bool handled,
6119 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006121 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006122
6123 { // Start critical section
6124 auto dispatchEntryIt =
6125 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6126 [seq](auto& e) { return e->seq == seq; });
6127 if (dispatchEntryIt == connection->waitQueue.end()) {
6128 return;
6129 }
6130
6131 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6132
6133 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6134 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6135 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6136 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6137 }
6138 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6139 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6140 connection->inputChannel->getConnectionToken(),
6141 dispatchEntry.deliveryTime, consumeTime, finishTime);
6142 }
6143
6144 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006145 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6146 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006147 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006148 }
6149 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006150
6151 // Dequeue the event and start the next cycle.
6152 // Because the lock might have been released, it is possible that the
6153 // contents of the wait queue to have been drained, so we need to double-check
6154 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006155 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6156 [seq](auto& e) { return e->seq == seq; });
6157 if (entryIt != connection->waitQueue.end()) {
6158 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6159 connection->waitQueue.erase(entryIt);
6160
Prabir Pradhancef936d2021-07-21 16:17:52 +00006161 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6162 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6163 if (!connection->responsive) {
6164 connection->responsive = isConnectionResponsive(*connection);
6165 if (connection->responsive) {
6166 // The connection was unresponsive, and now it's responsive.
6167 processConnectionResponsiveLocked(*connection);
6168 }
6169 }
6170 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006171 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6172 const InputTarget target{.inputChannel = connection->inputChannel,
6173 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006174 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006175 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006176 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006177 }
6178
6179 // Start the next dispatch cycle for this connection.
6180 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181}
6182
Prabir Pradhancef936d2021-07-21 16:17:52 +00006183void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6184 const sp<IBinder>& newToken) {
6185 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6186 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006187 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006188 };
6189 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190}
6191
Prabir Pradhancef936d2021-07-21 16:17:52 +00006192void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6193 auto command = [this, token, x, y]() REQUIRES(mLock) {
6194 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006195 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006196 };
6197 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006198}
6199
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006200void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006201 if (connection == nullptr) {
6202 LOG_ALWAYS_FATAL("Caller must check for nullness");
6203 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006204 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6205 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006206 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006207 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006208 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209 return;
6210 }
6211 /**
6212 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6213 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6214 * has changed. This could cause newer entries to time out before the already dispatched
6215 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6216 * processes the events linearly. So providing information about the oldest entry seems to be
6217 * most useful.
6218 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006219 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6220 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006221 std::string reason =
6222 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006223 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006224 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006225 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006226 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006227 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006228
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006229 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6230
6231 // Stop waking up for events on this connection, it is already unresponsive
6232 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006233}
6234
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006235void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6236 std::string reason =
6237 StringPrintf("%s does not have a focused window", application->getName().c_str());
6238 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006239
Yabin Cui8eb9c552023-06-08 18:05:07 +00006240 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006242 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006243 };
6244 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006245}
6246
chaviw98318de2021-05-19 16:45:23 -05006247void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006248 const std::string& reason) {
6249 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6250 updateLastAnrStateLocked(windowLabel, reason);
6251}
6252
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006253void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6254 const std::string& reason) {
6255 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006256 updateLastAnrStateLocked(windowLabel, reason);
6257}
6258
6259void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6260 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006262 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263 struct tm tm;
6264 localtime_r(&t, &tm);
6265 char timestr[64];
6266 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006267 mLastAnrState.clear();
6268 mLastAnrState += INDENT "ANR:\n";
6269 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006270 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6271 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006272 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273}
6274
Prabir Pradhancef936d2021-07-21 16:17:52 +00006275void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006276 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006277 const KeyEvent event = createKeyEvent(entry);
6278 nsecs_t delay = 0;
6279 { // release lock
6280 scoped_unlock unlock(mLock);
6281 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006282 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006283 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6284 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6285 std::to_string(t.duration().count()).c_str());
6286 }
6287 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006288
6289 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006290 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006291 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006292 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006293 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006294 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006295 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297}
6298
Prabir Pradhancef936d2021-07-21 16:17:52 +00006299void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006300 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006301 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006302 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006303 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006304 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305 };
6306 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006307}
6308
Prabir Pradhanedd96402022-02-15 01:46:16 -08006309void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006310 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006311 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006312 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006313 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006314 };
6315 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006316}
6317
6318/**
6319 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6320 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6321 * command entry to the command queue.
6322 */
6323void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6324 std::string reason) {
6325 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006326 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327 if (connection.monitor) {
6328 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6329 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006330 pid = findMonitorPidByTokenLocked(connectionToken);
6331 } else {
6332 // The connection is a window
6333 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6334 reason.c_str());
6335 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6336 if (handle != nullptr) {
6337 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006339 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006340 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006341}
6342
6343/**
6344 * Tell the policy that a connection has become responsive so that it can stop ANR.
6345 */
6346void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6347 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006348 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006349 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006350 pid = findMonitorPidByTokenLocked(connectionToken);
6351 } else {
6352 // The connection is a window
6353 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6354 if (handle != nullptr) {
6355 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006356 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006357 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006358 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006359}
6360
Prabir Pradhan24047542023-11-02 17:14:59 +00006361std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006362 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006363 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006364 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006365 if (!handled) {
6366 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006367 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006368 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006369 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006371
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006372 // Get the fallback key state.
6373 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006374 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006375 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006376 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006377 connection->inputState.removeFallbackKey(originalKeyCode);
6378 }
6379
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006380 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006381 // If the application handles the original key for which we previously
6382 // generated a fallback or if the window is not a foreground window,
6383 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006384 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006385 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006386 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6387 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6388 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6389 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6390 keyEntry.policyFlags);
6391 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006392 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006393 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394
6395 mLock.unlock();
6396
Prabir Pradhana41d2442023-04-20 21:30:40 +00006397 if (const auto unhandledKeyFallback =
6398 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6399 event, keyEntry.policyFlags);
6400 unhandledKeyFallback) {
6401 event = *unhandledKeyFallback;
6402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403
6404 mLock.lock();
6405
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006406 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006407 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006408 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006409 "application handled the original non-fallback key "
6410 "or is no longer a foreground target, "
6411 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006412 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006413 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006414 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006415 connection->inputState.removeFallbackKey(originalKeyCode);
6416 }
6417 } else {
6418 // If the application did not handle a non-fallback key, first check
6419 // that we are in a good state to perform unhandled key event processing
6420 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006421 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006422 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006423 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6424 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6425 "since this is not an initial down. "
6426 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6427 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6428 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006429 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006431
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006433 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6434 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6435 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6436 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6437 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006438 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439
6440 mLock.unlock();
6441
Prabir Pradhana41d2442023-04-20 21:30:40 +00006442 bool fallback = false;
6443 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6444 event, keyEntry.policyFlags);
6445 fb) {
6446 fallback = true;
6447 event = *fb;
6448 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006449
6450 mLock.lock();
6451
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006452 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006454 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 }
6456
6457 // Latch the fallback keycode for this key on an initial down.
6458 // The fallback keycode cannot change at any other point in the lifecycle.
6459 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006460 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006461 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006465 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006466 }
6467
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006468 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006469
6470 // Cancel the fallback key if the policy decides not to send it anymore.
6471 // We will continue to dispatch the key to the policy but we will no
6472 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6474 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006475 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6476 if (fallback) {
6477 ALOGD("Unhandled key event: Policy requested to send key %d"
6478 "as a fallback for %d, but on the DOWN it had requested "
6479 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006480 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006481 } else {
6482 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6483 "but on the DOWN it had requested to send %d. "
6484 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006485 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006486 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488
Michael Wrightfb04fd52022-11-24 22:31:11 +00006489 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006491 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006492 synthesizeCancelationEventsForConnectionLocked(connection, options);
6493
6494 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006495 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006496 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 }
6499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006501 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6502 {
6503 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006504 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006505 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 for (const auto& [key, value] : fallbackKeys) {
6507 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006508 }
6509 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6510 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513
6514 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006515 // Return the fallback key that we want dispatched to the channel.
6516 std::unique_ptr<KeyEntry> newEntry =
6517 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6518 event.getEventTime(), event.getDeviceId(),
6519 event.getSource(), event.getDisplayId(),
6520 keyEntry.policyFlags, keyEntry.action,
6521 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6522 *fallbackKeyCode, event.getScanCode(),
6523 event.getMetaState(), event.getRepeatCount(),
6524 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006525 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6526 ALOGD("Unhandled key event: Dispatching fallback key. "
6527 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006528 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006529 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006530 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006531 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006532 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6533 ALOGD("Unhandled key event: No fallback key.");
6534 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006535
6536 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006537 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006538 }
6539 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006540 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541}
6542
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543void InputDispatcher::traceInboundQueueLengthLocked() {
6544 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006545 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006546 }
6547}
6548
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006549void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550 if (ATRACE_ENABLED()) {
6551 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006552 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6553 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 }
6555}
6556
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006557void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 if (ATRACE_ENABLED()) {
6559 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006560 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6561 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 }
6563}
6564
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006565void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006566 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006568 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 dumpDispatchStateLocked(dump);
6570
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006571 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006572 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006573 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006574 }
6575}
6576
6577void InputDispatcher::monitor() {
6578 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006579 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006581 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582}
6583
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006584/**
6585 * Wake up the dispatcher and wait until it processes all events and commands.
6586 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6587 * this method can be safely called from any thread, as long as you've ensured that
6588 * the work you are interested in completing has already been queued.
6589 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006590bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006591 /**
6592 * Timeout should represent the longest possible time that a device might spend processing
6593 * events and commands.
6594 */
6595 constexpr std::chrono::duration TIMEOUT = 100ms;
6596 std::unique_lock lock(mLock);
6597 mLooper->wake();
6598 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6599 return result == std::cv_status::no_timeout;
6600}
6601
Vishnu Naire798b472020-07-23 13:52:21 -07006602/**
6603 * Sets focus to the window identified by the token. This must be called
6604 * after updating any input window handles.
6605 *
6606 * Params:
6607 * request.token - input channel token used to identify the window that should gain focus.
6608 * request.focusedToken - the token that the caller expects currently to be focused. If the
6609 * specified token does not match the currently focused window, this request will be dropped.
6610 * If the specified focused token matches the currently focused window, the call will succeed.
6611 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6612 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6613 * when requesting the focus change. This determines which request gets
6614 * precedence if there is a focus change request from another source such as pointer down.
6615 */
Vishnu Nair958da932020-08-21 17:12:37 -07006616void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6617 { // acquire lock
6618 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006619 std::optional<FocusResolver::FocusChanges> changes =
6620 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6621 if (changes) {
6622 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006623 }
6624 } // release lock
6625 // Wake up poll loop since it may need to make new input dispatching choices.
6626 mLooper->wake();
6627}
6628
Vishnu Nairc519ff72021-01-21 08:23:08 -08006629void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6630 if (changes.oldFocus) {
6631 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006632 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006633 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006634 "focus left window");
6635 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006636 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006637 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006638 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006639 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006640 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006641 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006642 }
6643
Prabir Pradhan99987712020-11-10 18:43:05 -08006644 // If a window has pointer capture, then it must have focus. We need to ensure that this
6645 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6646 // If the window loses focus before it loses pointer capture, then the window can be in a state
6647 // where it has pointer capture but not focus, violating the contract. Therefore we must
6648 // dispatch the pointer capture event before the focus event. Since focus events are added to
6649 // the front of the queue (above), we add the pointer capture event to the front of the queue
6650 // after the focus events are added. This ensures the pointer capture event ends up at the
6651 // front.
6652 disablePointerCaptureForcedLocked();
6653
Vishnu Nairc519ff72021-01-21 08:23:08 -08006654 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006655 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006656 }
6657}
Vishnu Nair958da932020-08-21 17:12:37 -07006658
Prabir Pradhan99987712020-11-10 18:43:05 -08006659void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006660 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006661 return;
6662 }
6663
6664 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6665
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006666 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006667 setPointerCaptureLocked(false);
6668 }
6669
6670 if (!mWindowTokenWithPointerCapture) {
6671 // No need to send capture changes because no window has capture.
6672 return;
6673 }
6674
6675 if (mPendingEvent != nullptr) {
6676 // Move the pending event to the front of the queue. This will give the chance
6677 // for the pending event to be dropped if it is a captured event.
6678 mInboundQueue.push_front(mPendingEvent);
6679 mPendingEvent = nullptr;
6680 }
6681
6682 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006683 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006684 mInboundQueue.push_front(std::move(entry));
6685}
6686
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006687void InputDispatcher::setPointerCaptureLocked(bool enable) {
6688 mCurrentPointerCaptureRequest.enable = enable;
6689 mCurrentPointerCaptureRequest.seq++;
6690 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006691 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006692 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006693 };
6694 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006695}
6696
Vishnu Nair599f1412021-06-21 10:39:58 -07006697void InputDispatcher::displayRemoved(int32_t displayId) {
6698 { // acquire lock
6699 std::scoped_lock _l(mLock);
6700 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006701 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006702 setFocusedApplicationLocked(displayId, nullptr);
6703 // Call focus resolver to clean up stale requests. This must be called after input windows
6704 // have been removed for the removed display.
6705 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006706 // Reset pointer capture eligibility, regardless of previous state.
6707 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006708 // Remove the associated touch mode state.
6709 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006710 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006711 } // release lock
6712
6713 // Wake up poll loop since it may need to make new input dispatching choices.
6714 mLooper->wake();
6715}
6716
Patrick Williamsd828f302023-04-28 17:52:08 -05006717void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006718 // The listener sends the windows as a flattened array. Separate the windows by display for
6719 // more convenient parsing.
6720 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006721 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006722 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006723 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006724 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006725
6726 { // acquire lock
6727 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006728
6729 // Ensure that we have an entry created for all existing displays so that if a displayId has
6730 // no windows, we can tell that the windows were removed from the display.
6731 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6732 handlesPerDisplay[displayId];
6733 }
6734
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006735 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006736 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006737 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6738 }
6739
6740 for (const auto& [displayId, handles] : handlesPerDisplay) {
6741 setInputWindowsLocked(handles, displayId);
6742 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006743
6744 if (update.vsyncId < mWindowInfosVsyncId) {
6745 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6746 ", current update vsync id: %" PRId64,
6747 mWindowInfosVsyncId, update.vsyncId);
6748 }
6749 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006750 }
6751 // Wake up poll loop since it may need to make new input dispatching choices.
6752 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006753}
6754
Vishnu Nair062a8672021-09-03 16:07:44 -07006755bool InputDispatcher::shouldDropInput(
6756 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006757 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6758 (windowHandle->getInfo()->inputConfig.test(
6759 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006760 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006761 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6762 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006763 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006764 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006765 windowHandle->getInfo()->displayId);
6766 return true;
6767 }
6768 return false;
6769}
6770
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006771void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006772 const gui::WindowInfosUpdate& update) {
6773 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006774}
6775
Arthur Hungdfd528e2021-12-08 13:23:04 +00006776void InputDispatcher::cancelCurrentTouch() {
6777 {
6778 std::scoped_lock _l(mLock);
6779 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006780 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006781 "cancel current touch");
6782 synthesizeCancelationEventsForAllConnectionsLocked(options);
6783
6784 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006785 }
6786 // Wake up poll loop since there might be work to do.
6787 mLooper->wake();
6788}
6789
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006790void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6791 std::scoped_lock _l(mLock);
6792 mMonitorDispatchingTimeout = timeout;
6793}
6794
Arthur Hungc539dbb2022-12-08 07:45:36 +00006795void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6796 const sp<WindowInfoHandle>& oldWindowHandle,
6797 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006798 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006799 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006800 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6801 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006802 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6803 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6804 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6805 newWindowHandle->getInfo()->inputConfig.test(
6806 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6807 const sp<WindowInfoHandle> oldWallpaper =
6808 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6809 const sp<WindowInfoHandle> newWallpaper =
6810 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6811 if (oldWallpaper == newWallpaper) {
6812 return;
6813 }
6814
6815 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006816 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006817 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
6818 oldTouchedWindow.targetFlags, pointerIds,
6819 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006820 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006821 }
6822
6823 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006824 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6825 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006826 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006827 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006828 }
6829}
6830
6831void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6832 ftl::Flags<InputTarget::Flags> newTargetFlags,
6833 const sp<WindowInfoHandle> fromWindowHandle,
6834 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006835 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006836 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006837 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6838 fromWindowHandle->getInfo()->inputConfig.test(
6839 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6840 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6841 toWindowHandle->getInfo()->inputConfig.test(
6842 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6843
6844 const sp<WindowInfoHandle> oldWallpaper =
6845 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6846 const sp<WindowInfoHandle> newWallpaper =
6847 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6848 if (oldWallpaper == newWallpaper) {
6849 return;
6850 }
6851
6852 if (oldWallpaper != nullptr) {
6853 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6854 "transferring touch focus to another window");
6855 state.removeWindowByToken(oldWallpaper->getToken());
6856 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6857 }
6858
6859 if (newWallpaper != nullptr) {
6860 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006861 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006862 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6863 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006864 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
6865 deviceId, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006866 std::shared_ptr<Connection> wallpaperConnection =
6867 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006868 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006869 std::shared_ptr<Connection> toConnection =
6870 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006871 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6872 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6873 wallpaperFlags);
6874 }
6875 }
6876}
6877
6878sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6879 const sp<WindowInfoHandle>& windowHandle) const {
6880 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6881 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6882 bool foundWindow = false;
6883 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6884 if (!foundWindow && otherHandle != windowHandle) {
6885 continue;
6886 }
6887 if (windowHandle == otherHandle) {
6888 foundWindow = true;
6889 continue;
6890 }
6891
6892 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6893 return otherHandle;
6894 }
6895 }
6896 return nullptr;
6897}
6898
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006899void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6900 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006901 std::scoped_lock _l(mLock);
6902
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006903 mConfig.keyRepeatTimeout = timeout.count();
6904 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006905}
6906
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006907bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6908 DeviceId deviceId, int32_t pointerId) {
6909 std::scoped_lock _l(mLock);
6910 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6911 if (touchStateIt == mTouchStatesByDisplay.end()) {
6912 return false;
6913 }
6914 for (const TouchedWindow& window : touchStateIt->second.windows) {
6915 if (window.windowHandle->getToken() == token &&
6916 (window.hasTouchingPointer(deviceId, pointerId) ||
6917 window.hasHoveringPointer(deviceId, pointerId))) {
6918 return true;
6919 }
6920 }
6921 return false;
6922}
6923
Garfield Tane84e6f92019-08-29 17:28:41 -07006924} // namespace android::inputdispatcher