blob: 7611d681a69908ede030315b61d7c3ff5817a7ab [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>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000035#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010037#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Michael Wright44753b12020-07-08 13:48:11 +010040#include <cerrno>
41#include <cinttypes>
42#include <climits>
43#include <cstddef>
44#include <ctime>
45#include <queue>
46#include <sstream>
47
48#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000049#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070050#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#define INDENT " "
53#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
56
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080057using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070058using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080059using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000060using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070062using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050063using android::gui::FocusRequest;
64using android::gui::TouchOcclusionMode;
65using android::gui::WindowInfo;
66using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080067using android::os::InputEventInjectionResult;
68using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069
Garfield Tane84e6f92019-08-29 17:28:41 -070070namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Prabir Pradhancef936d2021-07-21 16:17:52 +000072namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000073// Temporarily releases a held mutex for the lifetime of the instance.
74// Named to match std::scoped_lock
75class scoped_unlock {
76public:
77 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
78 ~scoped_unlock() { mMutex.lock(); }
79
80private:
81 std::mutex& mMutex;
82};
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// Default input dispatching timeout if there is no focused application or paused window
85// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080086const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
87 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
88 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for all pending events to be processed when an app switch
91// key is on the way. This is used to preempt input dispatch and drop input events
92// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700122inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000123 if (binder == nullptr) {
124 return "<null>";
125 }
126 return StringPrintf("%p", binder.get());
127}
128
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000129static std::string uidString(const gui::Uid& uid) {
130 return uid.toString();
131}
132
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
135 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136}
137
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500275 constexpr size_t maxEntries = 50; // max events to print
276 constexpr size_t skipBegin = maxEntries / 2;
277 const size_t skipEnd = queue.size() - maxEntries / 2;
278 // skip from maxEntries / 2 ... size() - maxEntries/2
279 // only print from 0 .. skipBegin and then from skipEnd .. size()
280
281 std::string dump;
282 for (size_t i = 0; i < queue.size(); i++) {
283 const DispatchEntry& entry = *queue[i];
284 if (i >= skipBegin && i < skipEnd) {
285 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
286 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
287 continue;
288 }
289 dump.append(INDENT4);
290 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800291 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
292 "ms",
293 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500294 ns2ms(currentTime - entry.eventEntry->eventTime));
295 if (entry.deliveryTime != 0) {
296 // This entry was delivered, so add information on how long we've been waiting
297 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
298 }
299 dump.append("\n");
300 }
301 return dump;
302}
303
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700304/**
305 * Find the entry in std::unordered_map by key, and return it.
306 * If the entry is not found, return a default constructed entry.
307 *
308 * Useful when the entries are vectors, since an empty vector will be returned
309 * if the entry is not found.
310 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
311 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700312template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700314 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800316}
317
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700319 if (first == second) {
320 return true;
321 }
322
323 if (first == nullptr || second == nullptr) {
324 return false;
325 }
326
327 return first->getToken() == second->getToken();
328}
329
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000330bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000331 if (first == nullptr || second == nullptr) {
332 return false;
333 }
334 return first->applicationInfo.token != nullptr &&
335 first->applicationInfo.token == second->applicationInfo.token;
336}
337
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800338template <typename T>
339size_t firstMarkedBit(T set) {
340 // TODO: replace with std::countr_zero from <bit> when that's available
341 LOG_ALWAYS_FATAL_IF(set.none());
342 size_t i = 0;
343 while (!set.test(i)) {
344 i++;
345 }
346 return i;
347}
348
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800349std::unique_ptr<DispatchEntry> createDispatchEntry(
350 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
351 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700352 if (inputTarget.useDefaultPointerTransform()) {
353 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700354 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700355 inputTarget.displayTransform,
356 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357 }
358
359 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
360 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
361
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700362 std::vector<PointerCoords> pointerCoords;
363 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364
365 // Use the first pointer information to normalize all other pointers. This could be any pointer
366 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 // uses the transform for the normalized pointer.
368 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800369 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371
372 // Iterate through all pointers in the event to normalize against the first.
373 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
374 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
375 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700376 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000377
378 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 // First, apply the current pointer's transform to update the coordinates into
380 // window space.
381 pointerCoords[pointerIndex].transform(currTransform);
382 // Next, apply the inverse transform of the normalized coordinates so the
383 // current coordinates are transformed into the normalized coordinate space.
384 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000385 }
386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::unique_ptr<MotionEntry> combinedMotionEntry =
388 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
389 motionEntry.deviceId, motionEntry.source,
390 motionEntry.displayId, motionEntry.policyFlags,
391 motionEntry.action, motionEntry.actionButton,
392 motionEntry.flags, motionEntry.metaState,
393 motionEntry.buttonState, motionEntry.classification,
394 motionEntry.edgeFlags, motionEntry.xPrecision,
395 motionEntry.yPrecision, motionEntry.xCursorPosition,
396 motionEntry.yCursorPosition, motionEntry.downTime,
397 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000398 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399
400 if (motionEntry.injectionState) {
401 combinedMotionEntry->injectionState = motionEntry.injectionState;
402 combinedMotionEntry->injectionState->refCount += 1;
403 }
404
405 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700406 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700407 firstPointerTransform, inputTarget.displayTransform,
408 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000409 return dispatchEntry;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
413 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700414 std::unique_ptr<InputChannel> uniqueServerChannel;
415 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
416
417 serverChannel = std::move(uniqueServerChannel);
418 return result;
419}
420
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500421template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000422bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500423 if (lhs == nullptr && rhs == nullptr) {
424 return true;
425 }
426 if (lhs == nullptr || rhs == nullptr) {
427 return false;
428 }
429 return *lhs == *rhs;
430}
431
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000432KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000433 KeyEvent event;
434 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
435 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
436 entry.repeatCount, entry.downTime, entry.eventTime);
437 return event;
438}
439
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000440bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000441 // Do not keep track of gesture monitors. They receive every event and would disproportionately
442 // affect the statistics.
443 if (connection.monitor) {
444 return false;
445 }
446 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
447 if (!connection.responsive) {
448 return false;
449 }
450 return true;
451}
452
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000453bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
455 const int32_t& inputEventId = eventEntry.id;
456 if (inputEventId != dispatchEntry.resolvedEventId) {
457 // Event was transmuted
458 return false;
459 }
460 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
461 return false;
462 }
463 // Only track latency for events that originated from hardware
464 if (eventEntry.isSynthesized()) {
465 return false;
466 }
467 const EventEntry::Type& inputEventEntryType = eventEntry.type;
468 if (inputEventEntryType == EventEntry::Type::KEY) {
469 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
470 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
471 return false;
472 }
473 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
474 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
475 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
476 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
477 return false;
478 }
479 } else {
480 // Not a key or a motion
481 return false;
482 }
483 if (!shouldReportMetricsForConnection(connection)) {
484 return false;
485 }
486 return true;
487}
488
Prabir Pradhancef936d2021-07-21 16:17:52 +0000489/**
490 * Connection is responsive if it has no events in the waitQueue that are older than the
491 * current time.
492 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000493bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000494 const nsecs_t currentTime = now();
495 for (const DispatchEntry* entry : connection.waitQueue) {
496 if (entry->timeoutTime < currentTime) {
497 return false;
498 }
499 }
500 return true;
501}
502
Antonio Kantekf16f2832021-09-28 04:39:20 +0000503// Returns true if the event type passed as argument represents a user activity.
504bool isUserActivityEvent(const EventEntry& eventEntry) {
505 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000506 case EventEntry::Type::CONFIGURATION_CHANGED:
507 case EventEntry::Type::DEVICE_RESET:
508 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000509 case EventEntry::Type::FOCUS:
510 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000511 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000512 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 case EventEntry::Type::KEY:
515 case EventEntry::Type::MOTION:
516 return true;
517 }
518}
519
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800520// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000521bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000522 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800523 const auto inputConfig = windowInfo.inputConfig;
524 if (windowInfo.displayId != displayId ||
525 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800526 return false;
527 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700528 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800529 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000532
533 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
534 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
535 // the window. Points on the right and bottom edges should not be inside the window, so we need
536 // to be careful about performing a hit test when the display is rotated, since the "right" and
537 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
538 // logical display in which WM determined the bounds. Perform the hit test in the logical
539 // display space to ensure these edges are considered correctly in all orientations.
540 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
541 const auto p = displayTransform.transform(x, y);
542 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800543 return false;
544 }
545 return true;
546}
547
Prabir Pradhand65552b2021-10-07 11:23:50 -0700548bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
549 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000550 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551}
552
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800553// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000554// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
555// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
556// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558bool canReceiveForegroundTouches(const WindowInfo& info) {
559 // A non-touchable window can still receive touch events (e.g. in the case of
560 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
561 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
562}
563
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000564bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700565 if (windowHandle == nullptr) {
566 return false;
567 }
568 const WindowInfo* windowInfo = windowHandle->getInfo();
569 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
570 return true;
571 }
572 return false;
573}
574
Prabir Pradhan5735a322022-04-11 17:23:34 +0000575// Checks targeted injection using the window's owner's uid.
576// Returns an empty string if an entry can be sent to the given window, or an error message if the
577// entry is a targeted injection whose uid target doesn't match the window owner.
578std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
579 const EventEntry& entry) {
580 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
581 // The event was not injected, or the injected event does not target a window.
582 return {};
583 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000584 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000585 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000586 return StringPrintf("No valid window target for injection into uid %s.",
587 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 }
589 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
591 "owned by uid %s.",
592 uid.toString().c_str(), window->getName().c_str(),
593 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000594 }
595 return {};
596}
597
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000598std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700599 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
600 // Always dispatch mouse events to cursor position.
601 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 }
604
605 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
607 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700608}
609
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700610std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
611 if (eventEntry.type == EventEntry::Type::KEY) {
612 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
613 return keyEntry.downTime;
614 } else if (eventEntry.type == EventEntry::Type::MOTION) {
615 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
616 return motionEntry.downTime;
617 }
618 return std::nullopt;
619}
620
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000621/**
622 * Compare the old touch state to the new touch state, and generate the corresponding touched
623 * windows (== input targets).
624 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
625 * If the pointer just entered the new window, produce HOVER_ENTER.
626 * For pointers remaining in the window, produce HOVER_MOVE.
627 */
628std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
629 const TouchState& newTouchState,
630 const MotionEntry& entry) {
631 std::vector<TouchedWindow> out;
632 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
633 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
634 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
635 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
636 // Not a hover event - don't need to do anything
637 return out;
638 }
639
640 // We should consider all hovering pointers here. But for now, just use the first one
641 const int32_t pointerId = entry.pointerProperties[0].id;
642
643 std::set<sp<WindowInfoHandle>> oldWindows;
644 if (oldState != nullptr) {
645 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
646 }
647
648 std::set<sp<WindowInfoHandle>> newWindows =
649 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
650
651 // If the pointer is no longer in the new window set, send HOVER_EXIT.
652 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
653 if (newWindows.find(oldWindow) == newWindows.end()) {
654 TouchedWindow touchedWindow;
655 touchedWindow.windowHandle = oldWindow;
656 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000657 out.push_back(touchedWindow);
658 }
659 }
660
661 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
662 TouchedWindow touchedWindow;
663 touchedWindow.windowHandle = newWindow;
664 if (oldWindows.find(newWindow) == oldWindows.end()) {
665 // Any windows that have this pointer now, and didn't have it before, should get
666 // HOVER_ENTER
667 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
668 } else {
669 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700670 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
671 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
672 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000673 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
674 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700675 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000676 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
677 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
678 }
679 out.push_back(touchedWindow);
680 }
681 return out;
682}
683
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800684template <typename T>
685std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
686 left.insert(left.end(), right.begin(), right.end());
687 return left;
688}
689
Harry Cuttsb166c002023-05-09 13:06:05 +0000690// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
691// both.
692void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
693 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
694 if (!window.windowHandle->getInfo()->inputConfig.test(
695 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
696 // In addition to TouchState, erase this window from the input targets! We don't have a
697 // good way to do this today except by adding a nested loop.
698 // TODO(b/282025641): simplify this code once InputTargets are being identified
699 // separately from TouchedWindows.
700 std::erase_if(targets, [&](const InputTarget& target) {
701 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
702 });
703 return true;
704 }
705 return false;
706 });
707}
708
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000709} // namespace
710
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711// --- InputDispatcher ---
712
Prabir Pradhana41d2442023-04-20 21:30:40 +0000713InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800714 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
715
Prabir Pradhana41d2442023-04-20 21:30:40 +0000716InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800717 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700718 : mPolicy(policy),
719 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700720 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800721 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700722 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700723 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700724 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800725 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 mDispatchEnabled(false),
727 mDispatchFrozen(false),
728 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100729 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000730 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800731 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800732 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000733 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000734 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700735 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800736 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700738 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700739#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700740 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700741#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700742 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743}
744
745InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000746 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747
Prabir Pradhancef936d2021-07-21 16:17:52 +0000748 resetKeyRepeatLocked();
749 releasePendingEventLocked();
750 drainInboundQueueLocked();
751 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000753 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700754 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000755 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757}
758
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700759status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700760 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700761 return ALREADY_EXISTS;
762 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700763 mThread = std::make_unique<InputThread>(
764 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
765 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700766}
767
768status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700769 if (mThread && mThread->isCallingThread()) {
770 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700771 return INVALID_OPERATION;
772 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700773 mThread.reset();
774 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700775}
776
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700778 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800780 std::scoped_lock _l(mLock);
781 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
783 // Run a dispatch loop if there are no pending commands.
784 // The dispatch loop might enqueue commands to run afterwards.
785 if (!haveCommandsLocked()) {
786 dispatchOnceInnerLocked(&nextWakeupTime);
787 }
788
789 // Run all pending commands if there are any.
790 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700792 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800794
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 // If we are still waiting for ack on some events,
796 // we might have to wake up earlier to check if an app is anr'ing.
797 const nsecs_t nextAnrCheck = processAnrsLocked();
798 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
799
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800800 // We are about to enter an infinitely long sleep, because we have no commands or
801 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700802 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800803 mDispatcherEnteredIdle.notify_all();
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 } // release lock
806
807 // Wait for callback or timeout or wake. (make sure we round up, not down)
808 nsecs_t currentTime = now();
809 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
810 mLooper->pollOnce(timeoutMillis);
811}
812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700813/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500814 * Raise ANR if there is no focused window.
815 * Before the ANR is raised, do a final state check:
816 * 1. The currently focused application must be the same one we are waiting for.
817 * 2. Ensure we still don't have a focused window.
818 */
819void InputDispatcher::processNoFocusedWindowAnrLocked() {
820 // Check if the application that we are waiting for is still focused.
821 std::shared_ptr<InputApplicationHandle> focusedApplication =
822 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
823 if (focusedApplication == nullptr ||
824 focusedApplication->getApplicationToken() !=
825 mAwaitedFocusedApplication->getApplicationToken()) {
826 // Unexpected because we should have reset the ANR timer when focused application changed
827 ALOGE("Waited for a focused window, but focused application has already changed to %s",
828 focusedApplication->getName().c_str());
829 return; // The focused application has changed.
830 }
831
chaviw98318de2021-05-19 16:45:23 -0500832 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500833 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
834 if (focusedWindowHandle != nullptr) {
835 return; // We now have a focused window. No need for ANR.
836 }
837 onAnrLocked(mAwaitedFocusedApplication);
838}
839
840/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700841 * Check if any of the connections' wait queues have events that are too old.
842 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
843 * Return the time at which we should wake up next.
844 */
845nsecs_t InputDispatcher::processAnrsLocked() {
846 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700847 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700848 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
849 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
850 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500851 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700852 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500853 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700854 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700855 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500856 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700857 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
858 }
859 }
860
861 // Check if any connection ANRs are due
862 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
863 if (currentTime < nextAnrCheck) { // most likely scenario
864 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
865 }
866
867 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700868 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700869 if (connection == nullptr) {
870 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
871 return nextAnrCheck;
872 }
873 connection->responsive = false;
874 // Stop waking up for this unresponsive connection
875 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000876 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700877 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700878}
879
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800880std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700881 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800882 if (connection->monitor) {
883 return mMonitorDispatchingTimeout;
884 }
885 const sp<WindowInfoHandle> window =
886 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700887 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500888 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700889 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500890 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891}
892
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
894 nsecs_t currentTime = now();
895
Jeff Browndc5992e2014-04-11 01:27:26 -0700896 // Reset the key repeat timer whenever normal dispatch is suspended while the
897 // device is in a non-interactive state. This is to ensure that we abort a key
898 // repeat if the device is just coming out of sleep.
899 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 resetKeyRepeatLocked();
901 }
902
903 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
904 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100905 if (DEBUG_FOCUS) {
906 ALOGD("Dispatch frozen. Waiting some more.");
907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 return;
909 }
910
911 // Optimize latency of app switches.
912 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
913 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
914 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
915 if (mAppSwitchDueTime < *nextWakeupTime) {
916 *nextWakeupTime = mAppSwitchDueTime;
917 }
918
919 // Ready to start a new event.
920 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700922 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 if (isAppSwitchDue) {
924 // The inbound queue is empty so the app switch key we were waiting
925 // for will never arrive. Stop waiting for it.
926 resetPendingAppSwitchLocked(false);
927 isAppSwitchDue = false;
928 }
929
930 // Synthesize a key repeat if appropriate.
931 if (mKeyRepeatState.lastKeyEntry) {
932 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
933 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
934 } else {
935 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
936 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
937 }
938 }
939 }
940
941 // Nothing to do if there is no pending event.
942 if (!mPendingEvent) {
943 return;
944 }
945 } else {
946 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700947 mPendingEvent = mInboundQueue.front();
948 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 traceInboundQueueLengthLocked();
950 }
951
952 // Poke user activity for this event.
953 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700954 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
957
958 // Now we have an event to dispatch.
959 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700960 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700962 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700964 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
968
969 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700970 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
972
973 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 const ConfigurationChangedEntry& typedEntry =
976 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700978 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 break;
980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 const DeviceResetEntry& typedEntry =
984 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700986 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 break;
988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100990 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 std::shared_ptr<FocusEntry> typedEntry =
992 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100993 dispatchFocusLocked(currentTime, typedEntry);
994 done = true;
995 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
996 break;
997 }
998
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700999 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1000 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1001 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1002 done = true;
1003 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1004 break;
1005 }
1006
Prabir Pradhan99987712020-11-10 18:43:05 -08001007 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1008 const auto typedEntry =
1009 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1010 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1011 done = true;
1012 break;
1013 }
1014
arthurhungb89ccb02020-12-30 16:19:01 +08001015 case EventEntry::Type::DRAG: {
1016 std::shared_ptr<DragEntry> typedEntry =
1017 std::static_pointer_cast<DragEntry>(mPendingEvent);
1018 dispatchDragLocked(currentTime, typedEntry);
1019 done = true;
1020 break;
1021 }
1022
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001024 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 resetPendingAppSwitchLocked(true);
1028 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 } else if (dropReason == DropReason::NOT_DROPPED) {
1030 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 }
1032 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001034 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001036 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1037 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001039 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 break;
1041 }
1042
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001043 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001044 std::shared_ptr<MotionEntry> motionEntry =
1045 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1047 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001052 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1053 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001055 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
Chris Yef59a2f42020-10-16 12:55:26 -07001058
1059 case EventEntry::Type::SENSOR: {
1060 std::shared_ptr<SensorEntry> sensorEntry =
1061 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1062 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1063 dropReason = DropReason::APP_SWITCH;
1064 }
1065 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1066 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1067 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1068 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1069 dropReason = DropReason::STALE;
1070 }
1071 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1072 done = true;
1073 break;
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076
1077 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001079 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
Michael Wright3a981722015-06-10 15:26:13 +01001081 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
1083 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001084 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086}
1087
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001088bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1089 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1090}
1091
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092/**
1093 * Return true if the events preceding this incoming motion event should be dropped
1094 * Return false otherwise (the default behaviour)
1095 */
1096bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001097 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001098 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001099
1100 // Optimize case where the current application is unresponsive and the user
1101 // decides to touch a window in a different application.
1102 // If the application takes too long to catch up then we drop all events preceding
1103 // the touch into the other window.
1104 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001105 const int32_t displayId = motionEntry.displayId;
1106 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001107 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001108
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001109 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001110 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001111 touchedWindowHandle->getApplicationToken() !=
1112 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001113 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001114 ALOGI("Pruning input queue because user touched a different application while waiting "
1115 "for %s",
1116 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001117 return true;
1118 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001119
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001120 // Alternatively, maybe there's a spy window that could handle this event.
1121 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1122 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1123 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001124 const std::shared_ptr<Connection> connection =
1125 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001126 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001127 // This spy window could take more input. Drop all events preceding this
1128 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001129 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001130 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001131 mAwaitedFocusedApplication->getName().c_str());
1132 return true;
1133 }
1134 }
1135 }
1136
1137 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1138 // yet been processed by some connections, the dispatcher will wait for these motion
1139 // events to be processed before dispatching the key event. This is because these motion events
1140 // may cause a new window to be launched, which the user might expect to receive focus.
1141 // To prevent waiting forever for such events, just send the key to the currently focused window
1142 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1143 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1144 "just send the pending key event to the focused window.");
1145 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001146 }
1147 return false;
1148}
1149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001151 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152 mInboundQueue.push_back(std::move(newEntry));
1153 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 traceInboundQueueLengthLocked();
1155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001158 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1159 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 // Optimize app switch latency.
1161 // If the application takes too long to catch up then we drop all events preceding
1162 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001163 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001165 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001169 if (DEBUG_APP_SWITCH) {
1170 ALOGD("App switch is pending!");
1171 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001172 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 mAppSwitchSawKeyDown = false;
1174 needWake = true;
1175 }
1176 }
1177 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001178
1179 // If a new up event comes in, and the pending event with same key code has been asked
1180 // to try again later because of the policy. We have to reset the intercept key wake up
1181 // time for it may have been handled in the policy and could be dropped.
1182 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1183 mPendingEvent->type == EventEntry::Type::KEY) {
1184 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1185 if (pendingKey.keyCode == keyEntry.keyCode &&
1186 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001187 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1188 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001189 pendingKey.interceptKeyWakeupTime = 0;
1190 needWake = true;
1191 }
1192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001193 break;
1194 }
1195
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001196 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001197 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1198 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1200 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001201 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001205 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001206 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1207 break;
1208 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001209 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001211 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001212 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001213 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1214 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001215 // nothing to do
1216 break;
1217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
1219
1220 return needWake;
1221}
1222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001224 // Do not store sensor event in recent queue to avoid flooding the queue.
1225 if (entry->type != EventEntry::Type::SENSOR) {
1226 mRecentQueue.push_back(entry);
1227 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001228 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001229 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 }
1231}
1232
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001233std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001234InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001235 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001237 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001238 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001239 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001240 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001241 continue;
1242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001244 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001245 if (!info.isSpy() &&
1246 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001247 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001248 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001249
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001250 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1251 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001252 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001253 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001256 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257}
1258
Prabir Pradhand65552b2021-10-07 11:23:50 -07001259std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001260 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001261 // Traverse windows from front to back and gather the touched spy windows.
1262 std::vector<sp<WindowInfoHandle>> spyWindows;
1263 const auto& windowHandles = getWindowHandlesLocked(displayId);
1264 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1265 const WindowInfo& info = *windowHandle->getInfo();
1266
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001267 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001268 continue;
1269 }
1270 if (!info.isSpy()) {
1271 // The first touched non-spy window was found, so return the spy windows touched so far.
1272 return spyWindows;
1273 }
1274 spyWindows.push_back(windowHandle);
1275 }
1276 return spyWindows;
1277}
1278
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001279void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 const char* reason;
1281 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001282 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001283 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001284 ALOGD("Dropped event because policy consumed it.");
1285 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001286 reason = "inbound event was dropped because the policy consumed it";
1287 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001288 case DropReason::DISABLED:
1289 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 ALOGI("Dropped event because input dispatch is disabled.");
1291 }
1292 reason = "inbound event was dropped because input dispatch is disabled";
1293 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001294 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 ALOGI("Dropped event because of pending overdue app switch.");
1296 reason = "inbound event was dropped because of pending overdue app switch";
1297 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001298 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 ALOGI("Dropped event because the current application is not responding and the user "
1300 "has started interacting with a different application.");
1301 reason = "inbound event was dropped because the current application is not responding "
1302 "and the user has started interacting with a different application";
1303 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001304 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 ALOGI("Dropped event because it is stale.");
1306 reason = "inbound event was dropped because it is stale";
1307 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001308 case DropReason::NO_POINTER_CAPTURE:
1309 ALOGI("Dropped event because there is no window with Pointer Capture.");
1310 reason = "inbound event was dropped because there is no window with Pointer Capture";
1311 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001312 case DropReason::NOT_DROPPED: {
1313 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001318 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001319 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001320 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001324 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001325 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1326 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001327 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 synthesizeCancelationEventsForAllConnectionsLocked(options);
1329 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001330 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1331 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 synthesizeCancelationEventsForAllConnectionsLocked(options);
1333 }
1334 break;
1335 }
Chris Yef59a2f42020-10-16 12:55:26 -07001336 case EventEntry::Type::SENSOR: {
1337 break;
1338 }
arthurhungb89ccb02020-12-30 16:19:01 +08001339 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1340 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001341 break;
1342 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001343 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001344 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001345 case EventEntry::Type::CONFIGURATION_CHANGED:
1346 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001347 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001348 break;
1349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
1351}
1352
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001353static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1355 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356}
1357
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001358bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1359 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1360 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1361 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362}
1363
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001364bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001365 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366}
1367
1368void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001369 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001371 if (DEBUG_APP_SWITCH) {
1372 if (handled) {
1373 ALOGD("App switch has arrived.");
1374 } else {
1375 ALOGD("App switch was abandoned.");
1376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378}
1379
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001381 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382}
1383
Prabir Pradhancef936d2021-07-21 16:17:52 +00001384bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001385 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 return false;
1387 }
1388
1389 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001390 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001391 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001392 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1393 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001394 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 return true;
1396}
1397
Prabir Pradhancef936d2021-07-21 16:17:52 +00001398void InputDispatcher::postCommandLocked(Command&& command) {
1399 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400}
1401
1402void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001403 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001404 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001405 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 releaseInboundEventLocked(entry);
1407 }
1408 traceInboundQueueLengthLocked();
1409}
1410
1411void InputDispatcher::releasePendingEventLocked() {
1412 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001414 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416}
1417
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001420 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001421 if (DEBUG_DISPATCH_CYCLE) {
1422 ALOGD("Injected inbound event was dropped.");
1423 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 }
1426 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001427 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 }
1429 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430}
1431
1432void InputDispatcher::resetKeyRepeatLocked() {
1433 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001434 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436}
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1439 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440
Michael Wright2e732952014-09-24 13:26:59 -07001441 uint32_t policyFlags = entry->policyFlags &
1442 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444 std::shared_ptr<KeyEntry> newEntry =
1445 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1446 entry->source, entry->displayId, policyFlags, entry->action,
1447 entry->flags, entry->keyCode, entry->scanCode,
1448 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001450 newEntry->syntheticRepeat = true;
1451 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454}
1455
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001457 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001458 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1459 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461
1462 // Reset key repeating in case a keyboard device was added or removed or something.
1463 resetKeyRepeatLocked();
1464
1465 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001466 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1467 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001468 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001469 };
1470 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 return true;
1472}
1473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001474bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1475 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001476 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1477 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1478 entry.deviceId);
1479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
liushenxiang42232912021-05-21 20:24:09 +08001481 // Reset key repeating in case a keyboard device was disabled or enabled.
1482 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1483 resetKeyRepeatLocked();
1484 }
1485
Michael Wrightfb04fd52022-11-24 22:31:11 +00001486 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001487 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001489
1490 // Remove all active pointers from this device
1491 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1492 touchState.removeAllPointersForDevice(entry.deviceId);
1493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 return true;
1495}
1496
Vishnu Nairad321cd2020-08-20 16:40:21 -07001497void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001499 if (mPendingEvent != nullptr) {
1500 // Move the pending event to the front of the queue. This will give the chance
1501 // for the pending event to get dispatched to the newly focused window
1502 mInboundQueue.push_front(mPendingEvent);
1503 mPendingEvent = nullptr;
1504 }
1505
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001506 std::unique_ptr<FocusEntry> focusEntry =
1507 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1508 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001509
1510 // This event should go to the front of the queue, but behind all other focus events
1511 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001512 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001513 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 [](const std::shared_ptr<EventEntry>& event) {
1515 return event->type == EventEntry::Type::FOCUS;
1516 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001517
1518 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001519 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001520}
1521
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001523 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001524 if (channel == nullptr) {
1525 return; // Window has gone away
1526 }
1527 InputTarget target;
1528 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001529 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001530 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001531 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1532 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001533 std::string reason = std::string("reason=").append(entry->reason);
1534 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001535 dispatchEventLocked(currentTime, entry, {target});
1536}
1537
Prabir Pradhan99987712020-11-10 18:43:05 -08001538void InputDispatcher::dispatchPointerCaptureChangedLocked(
1539 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1540 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001541 dropReason = DropReason::NOT_DROPPED;
1542
Prabir Pradhan99987712020-11-10 18:43:05 -08001543 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001544 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001545
1546 if (entry->pointerCaptureRequest.enable) {
1547 // Enable Pointer Capture.
1548 if (haveWindowWithPointerCapture &&
1549 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001550 // This can happen if pointer capture is disabled and re-enabled before we notify the
1551 // app of the state change, so there is no need to notify the app.
1552 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1553 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001554 }
1555 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001556 // This can happen if a window requests capture and immediately releases capture.
1557 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001558 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001559 return;
1560 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001561 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1562 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1563 return;
1564 }
1565
Vishnu Nairc519ff72021-01-21 08:23:08 -08001566 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001567 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1568 mWindowTokenWithPointerCapture = token;
1569 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001570 // Disable Pointer Capture.
1571 // We do not check if the sequence number matches for requests to disable Pointer Capture
1572 // for two reasons:
1573 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1574 // to disable capture with the same sequence number: one generated by
1575 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1576 // Capture being disabled in InputReader.
1577 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1578 // actual Pointer Capture state that affects events being generated by input devices is
1579 // in InputReader.
1580 if (!haveWindowWithPointerCapture) {
1581 // Pointer capture was already forcefully disabled because of focus change.
1582 dropReason = DropReason::NOT_DROPPED;
1583 return;
1584 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001585 token = mWindowTokenWithPointerCapture;
1586 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001587 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001588 setPointerCaptureLocked(false);
1589 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001590 }
1591
1592 auto channel = getInputChannelLocked(token);
1593 if (channel == nullptr) {
1594 // Window has gone away, clean up Pointer Capture state.
1595 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001596 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001597 setPointerCaptureLocked(false);
1598 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001599 return;
1600 }
1601 InputTarget target;
1602 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001603 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001604 entry->dispatchInProgress = true;
1605 dispatchEventLocked(currentTime, entry, {target});
1606
1607 dropReason = DropReason::NOT_DROPPED;
1608}
1609
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001610void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1611 const std::shared_ptr<TouchModeEntry>& entry) {
1612 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001613 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001614 if (windowHandles.empty()) {
1615 return;
1616 }
1617 const std::vector<InputTarget> inputTargets =
1618 getInputTargetsFromWindowHandlesLocked(windowHandles);
1619 if (inputTargets.empty()) {
1620 return;
1621 }
1622 entry->dispatchInProgress = true;
1623 dispatchEventLocked(currentTime, entry, inputTargets);
1624}
1625
1626std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1627 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1628 std::vector<InputTarget> inputTargets;
1629 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001630 const sp<IBinder>& token = handle->getToken();
1631 if (token == nullptr) {
1632 continue;
1633 }
1634 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1635 if (channel == nullptr) {
1636 continue; // Window has gone away
1637 }
1638 InputTarget target;
1639 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001640 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001641 inputTargets.push_back(target);
1642 }
1643 return inputTargets;
1644}
1645
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001646bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 if (!entry->dispatchInProgress) {
1650 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1651 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1652 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1653 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001654 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 // We have seen two identical key downs in a row which indicates that the device
1656 // driver is automatically generating key repeats itself. We take note of the
1657 // repeat here, but we disable our own next key repeat timer since it is clear that
1658 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001659 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1660 // Make sure we don't get key down from a different device. If a different
1661 // device Id has same key pressed down, the new device Id will replace the
1662 // current one to hold the key repeat with repeat count reset.
1663 // In the future when got a KEY_UP on the device id, drop it and do not
1664 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1666 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001667 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 } else {
1669 // Not a repeat. Save key down state in case we do see a repeat later.
1670 resetKeyRepeatLocked();
1671 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1672 }
1673 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001674 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1675 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001676 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001677 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001678 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1679 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 resetKeyRepeatLocked();
1682 }
1683
1684 if (entry->repeatCount == 1) {
1685 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1686 } else {
1687 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1688 }
1689
1690 entry->dispatchInProgress = true;
1691
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001692 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
1694
1695 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001696 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 if (currentTime < entry->interceptKeyWakeupTime) {
1698 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1699 *nextWakeupTime = entry->interceptKeyWakeupTime;
1700 }
1701 return false; // wait until next wakeup
1702 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001703 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 entry->interceptKeyWakeupTime = 0;
1705 }
1706
1707 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001708 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001710 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001711 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001712
1713 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1714 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1715 };
1716 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001717 // Poke user activity for keys not passed to user
1718 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 return false; // wait for the command to run
1720 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001721 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001723 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001724 if (*dropReason == DropReason::NOT_DROPPED) {
1725 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 }
1727 }
1728
1729 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001730 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001731 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001732 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1733 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001734 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001735 // Poke user activity for undispatched keys
1736 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 return true;
1738 }
1739
1740 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001741 InputEventInjectionResult injectionResult;
1742 sp<WindowInfoHandle> focusedWindow =
1743 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1744 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 return false;
1747 }
1748
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001749 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 return true;
1752 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001753 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1754
1755 std::vector<InputTarget> inputTargets;
1756 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001757 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001758 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001760 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762
1763 // Dispatch the key.
1764 dispatchEventLocked(currentTime, entry, inputTargets);
1765 return true;
1766}
1767
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001768void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001769 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1770 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1771 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1772 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1773 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1774 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1775 entry.metaState, entry.repeatCount, entry.downTime);
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777}
1778
Prabir Pradhancef936d2021-07-21 16:17:52 +00001779void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1780 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001781 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001782 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1783 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1784 "source=0x%x, sensorType=%s",
1785 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001786 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001787 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001788 auto command = [this, entry]() REQUIRES(mLock) {
1789 scoped_unlock unlock(mLock);
1790
1791 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001792 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001793 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001794 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1795 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001796 };
1797 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001798}
1799
1800bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001801 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1802 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001803 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001804 }
Chris Yef59a2f42020-10-16 12:55:26 -07001805 { // acquire lock
1806 std::scoped_lock _l(mLock);
1807
1808 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1809 std::shared_ptr<EventEntry> entry = *it;
1810 if (entry->type == EventEntry::Type::SENSOR) {
1811 it = mInboundQueue.erase(it);
1812 releaseInboundEventLocked(entry);
1813 }
1814 }
1815 }
1816 return true;
1817}
1818
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001819bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001821 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 entry->dispatchInProgress = true;
1825
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
1828
1829 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001830 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001831 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1833 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 return true;
1835 }
1836
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001837 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838
1839 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001840 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841
1842 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 if (isPointerEvent) {
1845 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001846
1847 if (mDragState &&
1848 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1849 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1850 pilferPointersLocked(mDragState->dragWindow->getToken());
1851 }
1852
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001853 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001854 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001855 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001856 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1857 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 } else {
1859 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001860 sp<WindowInfoHandle> focusedWindow =
1861 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1862 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1863 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1864 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001865 InputTarget::Flags::FOREGROUND |
1866 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001867 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001870 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 return false;
1872 }
1873
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001874 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001875 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001876 return true;
1877 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001879 CancelationOptions::Mode mode(
1880 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1881 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001882 CancelationOptions options(mode, "input event injection failed");
1883 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 return true;
1885 }
1886
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001887 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001888 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889
1890 // Dispatch the motion.
1891 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001892 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 synthesizeCancelationEventsForAllConnectionsLocked(options);
1895 }
1896 dispatchEventLocked(currentTime, entry, inputTargets);
1897 return true;
1898}
1899
chaviw98318de2021-05-19 16:45:23 -05001900void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001901 bool isExiting, const int32_t rawX,
1902 const int32_t rawY) {
1903 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001904 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001905 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1906 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001907
1908 enqueueInboundEventLocked(std::move(dragEntry));
1909}
1910
1911void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1912 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1913 if (channel == nullptr) {
1914 return; // Window has gone away
1915 }
1916 InputTarget target;
1917 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001918 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001919 entry->dispatchInProgress = true;
1920 dispatchEventLocked(currentTime, entry, {target});
1921}
1922
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001924 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001925 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001926 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001927 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001928 "metaState=0x%x, buttonState=0x%x,"
1929 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001930 prefix, entry.eventTime, entry.deviceId,
1931 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1932 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1933 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1934 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001936 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001937 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 "x=%f, y=%f, pressure=%f, size=%f, "
1939 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1940 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001941 i, entry.pointerProperties[i].id,
1942 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001943 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1944 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1945 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1946 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1947 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1948 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1949 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1950 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954}
1955
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001956void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1957 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001960 if (DEBUG_DISPATCH_CYCLE) {
1961 ALOGD("dispatchEventToCurrentInputTargets");
1962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001964 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001965
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1967
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001968 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001970 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001971 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001972 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001973 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001974 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001976 if (DEBUG_FOCUS) {
1977 ALOGD("Dropping event delivery to target with channel '%s' because it "
1978 "is no longer registered with the input dispatcher.",
1979 inputTarget.inputChannel->getName().c_str());
1980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 }
1982 }
1983}
1984
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001985void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1987 // If the policy decides to close the app, we will get a channel removal event via
1988 // unregisterInputChannel, and will clean up the connection that way. We are already not
1989 // sending new pointers to the connection when it blocked, but focused events will continue to
1990 // pile up.
1991 ALOGW("Canceling events for %s because it is unresponsive",
1992 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001993 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001994 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995 "application not responding");
1996 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998}
1999
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002000void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002001 if (DEBUG_FOCUS) {
2002 ALOGD("Resetting ANR timeouts.");
2003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
2005 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002006 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002007 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008}
2009
Tiger Huang721e26f2018-07-24 22:26:19 +08002010/**
2011 * Get the display id that the given event should go to. If this event specifies a valid display id,
2012 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2013 * Focused display is the display that the user most recently interacted with.
2014 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002015int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002016 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002017 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002018 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2020 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002021 break;
2022 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002023 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2025 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002026 break;
2027 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002028 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002029 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002030 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002031 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002032 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002033 case EventEntry::Type::SENSOR:
2034 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002035 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 return ADISPLAY_ID_NONE;
2037 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002038 }
2039 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2040}
2041
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002042bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2043 const char* focusedWindowName) {
2044 if (mAnrTracker.empty()) {
2045 // already processed all events that we waited for
2046 mKeyIsWaitingForEventsTimeout = std::nullopt;
2047 return false;
2048 }
2049
2050 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2051 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002052 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002053 mKeyIsWaitingForEventsTimeout = currentTime +
2054 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2055 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 return true;
2057 }
2058
2059 // We still have pending events, and already started the timer
2060 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2061 return true; // Still waiting
2062 }
2063
2064 // Waited too long, and some connection still hasn't processed all motions
2065 // Just send the key to the focused window
2066 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2067 focusedWindowName);
2068 mKeyIsWaitingForEventsTimeout = std::nullopt;
2069 return false;
2070}
2071
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002072sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2073 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2074 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002075 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002076 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077
Tiger Huang721e26f2018-07-24 22:26:19 +08002078 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002079 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002080 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002081 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2082
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 // If there is no currently focused window and no focused application
2084 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2086 ALOGI("Dropping %s event because there is no focused window or focused application in "
2087 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002088 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002089 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091
Vishnu Nair062a8672021-09-03 16:07:44 -07002092 // Drop key events if requested by input feature
2093 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002094 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002095 }
2096
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002097 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2098 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2099 // start interacting with another application via touch (app switch). This code can be removed
2100 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2101 // an app is expected to have a focused window.
2102 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2103 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2104 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002105 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2106 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2107 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002108 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002109 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 ALOGW("Waiting because no window has focus but %s may eventually add a "
2111 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002112 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002114 outInjectionResult = InputEventInjectionResult::PENDING;
2115 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2117 // Already raised ANR. Drop the event
2118 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002119 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002120 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 } else {
2122 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002123 outInjectionResult = InputEventInjectionResult::PENDING;
2124 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 }
2126 }
2127
2128 // we have a valid, non-null focused window
2129 resetNoFocusedWindowTimeoutLocked();
2130
Prabir Pradhan5735a322022-04-11 17:23:34 +00002131 // Verify targeted injection.
2132 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2133 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002134 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2135 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002138 if (focusedWindowHandle->getInfo()->inputConfig.test(
2139 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002140 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002141 outInjectionResult = InputEventInjectionResult::PENDING;
2142 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002143 }
2144
2145 // If the event is a key event, then we must wait for all previous events to
2146 // complete before delivering it because previous events may have the
2147 // side-effect of transferring focus to a different window and we want to
2148 // ensure that the following keys are sent to the new window.
2149 //
2150 // Suppose the user touches a button in a window then immediately presses "A".
2151 // If the button causes a pop-up window to appear then we want to ensure that
2152 // the "A" key is delivered to the new pop-up window. This is because users
2153 // often anticipate pending UI changes when typing on a keyboard.
2154 // To obtain this behavior, we must serialize key events with respect to all
2155 // prior input events.
2156 if (entry.type == EventEntry::Type::KEY) {
2157 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2158 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 outInjectionResult = InputEventInjectionResult::PENDING;
2160 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002164 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2165 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166}
2167
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002168/**
2169 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2170 * that are currently unresponsive.
2171 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002172std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2173 const std::vector<Monitor>& monitors) const {
2174 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002176 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002177 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002178 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 if (connection == nullptr) {
2180 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002181 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 return false;
2183 }
2184 if (!connection->responsive) {
2185 ALOGW("Unresponsive monitor %s will not get the new gesture",
2186 connection->inputChannel->getName().c_str());
2187 return false;
2188 }
2189 return true;
2190 });
2191 return responsiveMonitors;
2192}
2193
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002194/**
2195 * In general, touch should be always split between windows. Some exceptions:
2196 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002197 * from the same device, *and* the window that's receiving the current pointer does not support
2198 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002199 * 2. Don't split mouse events
2200 */
2201bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2202 const MotionEntry& entry) const {
2203 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2204 // We should never split mouse events
2205 return false;
2206 }
2207 for (const TouchedWindow& touchedWindow : touchState.windows) {
2208 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2209 // Spy windows should not affect whether or not touch is split.
2210 continue;
2211 }
2212 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2213 continue;
2214 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002215 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2216 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2217 // Wallpaper window should not affect whether or not touch is split
2218 continue;
2219 }
2220
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002221 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002222 return false;
2223 }
2224 }
2225 return true;
2226}
2227
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002228std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002229 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2230 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002231 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002233 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 // For security reasons, we defer updating the touch state until we are sure that
2235 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002236 const int32_t displayId = entry.displayId;
2237 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002238 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239
2240 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002241 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002243 // Copy current touch state into tempTouchState.
2244 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2245 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002246 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002248 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2249 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002250 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002251 }
2252
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002253 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002254 bool switchedDevice = false;
2255 if (oldState != nullptr) {
2256 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2257 const bool anotherDeviceIsActive =
2258 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2259 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002260 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002261
2262 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2263 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2264 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002265 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2266 // touchable windows.
2267 const bool wasDown = oldState != nullptr && oldState->isDown();
2268 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2269 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002270 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2272 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002273 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002274
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002275 // If pointers are already down, let's finish the current gesture and ignore the new events
2276 // from another device. However, if the new event is a down event, let's cancel the current
2277 // touch and let the new one take over.
2278 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002279 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002280 << " is already down in display " << displayId << ": " << entry.getDescription();
2281 // TODO(b/211379801): test multiple simultaneous input streams.
2282 outInjectionResult = InputEventInjectionResult::FAILED;
2283 return {}; // wrong device
2284 }
2285
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002287 // If a new gesture is starting, clear the touch state completely.
2288 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002290 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002291 ALOGI("Dropping move event because a pointer for a different device is already active "
2292 "in display %" PRId32,
2293 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002294 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002295 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002296 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002299 if (isHoverAction) {
2300 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2301 // all of the existing hovering pointers and recompute.
2302 tempTouchState.clearHoveringPointers();
2303 }
2304
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2306 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002307 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002309 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2310 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002311 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002312 auto [newTouchedWindowHandle, outsideTargets] =
2313 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002314
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002315 if (isDown) {
2316 targets += outsideTargets;
2317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002319 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002320 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002323 }
2324
Prabir Pradhan5735a322022-04-11 17:23:34 +00002325 // Verify targeted injection.
2326 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2327 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002328 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002329 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002330 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002331 }
2332
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002333 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002334 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002335 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2336 // New window supports splitting, but we should never split mouse events.
2337 isSplit = !isFromMouse;
2338 } else if (isSplit) {
2339 // New window does not support splitting but we have already split events.
2340 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002341 newTouchedWindowHandle = nullptr;
2342 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002343 } else {
2344 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002345 // be delivered to a new window which supports split touch. Pointers from a mouse device
2346 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002347 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002348 }
2349
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002350 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002351 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002352 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002353 // Process the foreground window first so that it is the first to receive the event.
2354 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002355 }
2356
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002357 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002358 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2359 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002360 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002361 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002362 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002363 }
2364
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002366 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002367 continue;
2368 }
2369
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002370 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2371 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002372 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002373 // The "windowHandle" is the target of this hovering pointer.
2374 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002375 }
2376
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002377 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002378 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002380 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2381 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002382 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002383 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384
2385 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002386 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387 }
2388 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002389 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002390 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002391 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002393
2394 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002395 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002396 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002397 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002398 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002400 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2401 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2402
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002403 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2404 // still add a window to the touch state. We should avoid doing that, but some of the
2405 // later checks ("at least one foreground window") rely on this in order to dispatch
2406 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002407 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002408 isDownOrPointerDown
2409 ? std::make_optional(entry.eventTime)
2410 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002411
2412 // If this is the pointer going down and the touched window has a wallpaper
2413 // then also add the touched wallpaper windows so they are locked in for the duration
2414 // of the touch gesture.
2415 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2416 // engine only supports touch events. We would need to add a mechanism similar
2417 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002418 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002419 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2420 windowHandle->getInfo()->inputConfig.test(
2421 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2422 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2423 if (wallpaper != nullptr) {
2424 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2425 InputTarget::Flags::WINDOW_IS_OBSCURED |
2426 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2427 InputTarget::Flags::DISPATCH_AS_IS;
2428 if (isSplit) {
2429 wallpaperFlags |= InputTarget::Flags::SPLIT;
2430 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002431 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2432 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002433 }
2434 }
2435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002437
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002438 // If a window is already pilfering some pointers, give it this new pointer as well and
2439 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2440 // which is a specific behaviour that we want.
2441 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2442 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002443 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2444 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002445 // This window is already pilfering some pointers, and this new pointer is also
2446 // going to it. Therefore, take over this pointer and don't give it to anyone
2447 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002448 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002449 }
2450 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002451
2452 // Restrict all pilfered pointers to the pilfering windows.
2453 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 } else {
2455 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2456
2457 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002458 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002459 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2460 "dropped the pointer down event in display "
2461 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002462 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002463 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002466 // If the pointer is not currently hovering, then ignore the event.
2467 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2468 const int32_t pointerId = entry.pointerProperties[0].id;
2469 if (oldState == nullptr ||
2470 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2471 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2472 "display "
2473 << displayId << ": " << entry.getDescription();
2474 outInjectionResult = InputEventInjectionResult::FAILED;
2475 return {};
2476 }
2477 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2478 }
2479
arthurhung6d4bed92021-03-17 11:59:33 +08002480 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002481
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002483 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002484 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002485 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002486 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002487 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002488 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002489 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002490 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002491
Prabir Pradhan5735a322022-04-11 17:23:34 +00002492 // Verify targeted injection.
2493 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2494 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002495 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002496 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002497 }
2498
Vishnu Nair062a8672021-09-03 16:07:44 -07002499 // Drop touch events if requested by input feature
2500 if (newTouchedWindowHandle != nullptr &&
2501 shouldDropInput(entry, newTouchedWindowHandle)) {
2502 newTouchedWindowHandle = nullptr;
2503 }
2504
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002505 if (newTouchedWindowHandle != nullptr &&
2506 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002507 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2508 oldTouchedWindowHandle->getName().c_str(),
2509 newTouchedWindowHandle->getName().c_str(), displayId);
2510
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002512 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002513 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002514 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002515
2516 const TouchedWindow& touchedWindow =
2517 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2518 addWindowTargetLocked(oldTouchedWindowHandle,
2519 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002520 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521
2522 // Make a slippery entrance into the new window.
2523 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002524 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 }
2526
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002527 ftl::Flags<InputTarget::Flags> targetFlags =
2528 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002529 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002530 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002533 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
2535 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002536 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002537 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002538 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002541 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2542 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002543
2544 // Check if the wallpaper window should deliver the corresponding event.
2545 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002546 tempTouchState, entry.deviceId, pointerId, targets);
2547 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2548 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
2550 }
Arthur Hung96483742022-11-15 03:30:48 +00002551
2552 // Update the pointerIds for non-splittable when it received pointer down.
2553 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2554 // If no split, we suppose all touched windows should receive pointer down.
2555 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2556 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2557 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2558 // Ignore drag window for it should just track one pointer.
2559 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2560 continue;
2561 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002562 touchedWindow.addTouchingPointer(entry.deviceId,
2563 entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002564 }
2565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 }
2567
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002568 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002569 {
2570 std::vector<TouchedWindow> hoveringWindows =
2571 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2572 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002573 std::optional<InputTarget> target =
2574 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002575 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002576 if (!target) {
2577 continue;
2578 }
2579 // Hardcode to single hovering pointer for now.
2580 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2581 pointerIds.set(entry.pointerProperties[0].id);
2582 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2583 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586
Prabir Pradhan5735a322022-04-11 17:23:34 +00002587 // Ensure that all touched windows are valid for injection.
2588 if (entry.injectionState != nullptr) {
2589 std::string errs;
2590 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002591 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2592 if (err) errs += "\n - " + *err;
2593 }
2594 if (!errs.empty()) {
2595 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002596 "%s:%s",
2597 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002598 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002599 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002600 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002601 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002602
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002603 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2604 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002606 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002607 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002608 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002609 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002610 for (InputTarget& target : targets) {
2611 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2612 sp<WindowInfoHandle> targetWindow =
2613 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2614 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2615 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 }
2618 }
2619 }
2620 }
2621
Harry Cuttsb166c002023-05-09 13:06:05 +00002622 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2623 // only want the system UI to handle these gestures.
2624 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2625 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2626 if (isTouchpadNavGesture) {
2627 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2628 }
2629
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002630 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002631 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002632 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2633 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002634 // Windows with hovering pointers are getting persisted inside TouchState.
2635 // Do not send this event to those windows.
2636 continue;
2637 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002638
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002639 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002640 touchedWindow.getTouchingPointers(entry.deviceId),
2641 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002642 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002643
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002644 // During targeted injection, only allow owned targets to receive events
2645 std::erase_if(targets, [&](const InputTarget& target) {
2646 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2647 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2648 if (err) {
2649 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2650 << ": " << (*err);
2651 return true;
2652 }
2653 return false;
2654 });
2655
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002656 if (targets.empty()) {
2657 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2658 outInjectionResult = InputEventInjectionResult::FAILED;
2659 return {};
2660 }
2661
2662 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2663 // window that is actually receiving the entire gesture.
2664 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2665 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2666 })) {
2667 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2668 << entry.getDescription();
2669 outInjectionResult = InputEventInjectionResult::FAILED;
2670 return {};
2671 }
2672
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002673 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002674 // Drop the outside or hover touch windows since we will not care about them
2675 // in the next iteration.
2676 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002679 if (switchedDevice) {
2680 if (DEBUG_FOCUS) {
2681 ALOGD("Conflicting pointer actions: Switched to a different device.");
2682 }
2683 *outConflictingPointerActions = true;
2684 }
2685
2686 if (isHoverAction) {
2687 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002688 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002689 ALOGD_IF(DEBUG_FOCUS,
2690 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002691 *outConflictingPointerActions = true;
2692 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002693 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2694 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002695 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002696 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002697 // All pointers up or canceled.
2698 tempTouchState.reset();
2699 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2700 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002701 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2702 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002703 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002704 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002705 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2706 // One pointer went up.
2707 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2708 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002710 for (size_t i = 0; i < tempTouchState.windows.size();) {
2711 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002712 touchedWindow.removeTouchingPointer(entry.deviceId, pointerId);
2713 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2715 continue;
2716 }
2717 i += 1;
2718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 }
2720
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002721 // Save changes unless the action was scroll in which case the temporary touch
2722 // state was only valid for this one action.
2723 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002724 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002725 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002726 mTouchStatesByDisplay[displayId] = tempTouchState;
2727 } else {
2728 mTouchStatesByDisplay.erase(displayId);
2729 }
2730 }
2731
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002732 if (tempTouchState.windows.empty()) {
2733 mTouchStatesByDisplay.erase(displayId);
2734 }
2735
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002736 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737}
2738
arthurhung6d4bed92021-03-17 11:59:33 +08002739void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002740 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2741 // have an explicit reason to support it.
2742 constexpr bool isStylus = false;
2743
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002744 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002745 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002746 if (dropWindow) {
2747 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002748 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002749 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002750 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002751 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002752 }
2753 mDragState.reset();
2754}
2755
2756void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002757 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002758 return;
2759 }
2760
arthurhung6d4bed92021-03-17 11:59:33 +08002761 if (!mDragState->isStartDrag) {
2762 mDragState->isStartDrag = true;
2763 mDragState->isStylusButtonDownAtStart =
2764 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2765 }
2766
Arthur Hung54745652022-04-20 07:17:41 +00002767 // Find the pointer index by id.
2768 int32_t pointerIndex = 0;
2769 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2770 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2771 if (pointerProperties.id == mDragState->pointerId) {
2772 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002773 }
Arthur Hung54745652022-04-20 07:17:41 +00002774 }
arthurhung6d4bed92021-03-17 11:59:33 +08002775
Arthur Hung54745652022-04-20 07:17:41 +00002776 if (uint32_t(pointerIndex) == entry.pointerCount) {
2777 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002778 }
2779
2780 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2781 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2782 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2783
2784 switch (maskedAction) {
2785 case AMOTION_EVENT_ACTION_MOVE: {
2786 // Handle the special case : stylus button no longer pressed.
2787 bool isStylusButtonDown =
2788 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2789 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2790 finishDragAndDrop(entry.displayId, x, y);
2791 return;
2792 }
2793
2794 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2795 // until we have an explicit reason to support it.
2796 constexpr bool isStylus = false;
2797
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002798 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002799 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002800 // enqueue drag exit if needed.
2801 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2802 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2803 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002804 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002805 y);
2806 }
2807 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2808 }
2809 // enqueue drag location if needed.
2810 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002811 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002812 }
2813 break;
2814 }
2815
2816 case AMOTION_EVENT_ACTION_POINTER_UP:
2817 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2818 break;
2819 }
2820 // The drag pointer is up.
2821 [[fallthrough]];
2822 case AMOTION_EVENT_ACTION_UP:
2823 finishDragAndDrop(entry.displayId, x, y);
2824 break;
2825 case AMOTION_EVENT_ACTION_CANCEL: {
2826 ALOGD("Receiving cancel when drag and drop.");
2827 sendDropWindowCommandLocked(nullptr, 0, 0);
2828 mDragState.reset();
2829 break;
2830 }
arthurhungb89ccb02020-12-30 16:19:01 +08002831 }
2832}
2833
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002834std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2835 const sp<android::gui::WindowInfoHandle>& windowHandle,
2836 ftl::Flags<InputTarget::Flags> targetFlags,
2837 std::optional<nsecs_t> firstDownTimeInTarget) const {
2838 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2839 if (inputChannel == nullptr) {
2840 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2841 return {};
2842 }
2843 InputTarget inputTarget;
2844 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002845 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002846 inputTarget.flags = targetFlags;
2847 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2848 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2849 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2850 if (displayInfoIt != mDisplayInfos.end()) {
2851 inputTarget.displayTransform = displayInfoIt->second.transform;
2852 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002853 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002854 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2855 }
2856 return inputTarget;
2857}
2858
chaviw98318de2021-05-19 16:45:23 -05002859void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002860 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002861 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002862 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002863 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002864 std::vector<InputTarget>::iterator it =
2865 std::find_if(inputTargets.begin(), inputTargets.end(),
2866 [&windowHandle](const InputTarget& inputTarget) {
2867 return inputTarget.inputChannel->getConnectionToken() ==
2868 windowHandle->getToken();
2869 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002870
chaviw98318de2021-05-19 16:45:23 -05002871 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002872
2873 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002874 std::optional<InputTarget> target =
2875 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2876 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002877 return;
2878 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002879 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002880 it = inputTargets.end() - 1;
2881 }
2882
2883 ALOG_ASSERT(it->flags == targetFlags);
2884 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2885
chaviw1ff3d1e2020-07-01 15:53:47 -07002886 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887}
2888
Michael Wright3dd60e22019-03-27 22:06:44 +00002889void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002890 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002891 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2892 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002893
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002894 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2895 InputTarget target;
2896 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002897 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002898 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2899 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002900 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2901 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002902 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002903 target.setDefaultPointerTransform(target.displayTransform);
2904 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 }
2906}
2907
Robert Carrc9bf1d32020-04-13 17:21:08 -07002908/**
2909 * Indicate whether one window handle should be considered as obscuring
2910 * another window handle. We only check a few preconditions. Actually
2911 * checking the bounds is left to the caller.
2912 */
chaviw98318de2021-05-19 16:45:23 -05002913static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2914 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002915 // Compare by token so cloned layers aren't counted
2916 if (haveSameToken(windowHandle, otherHandle)) {
2917 return false;
2918 }
2919 auto info = windowHandle->getInfo();
2920 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002921 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002922 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002923 } else if (otherInfo->alpha == 0 &&
2924 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002925 // Those act as if they were invisible, so we don't need to flag them.
2926 // We do want to potentially flag touchable windows even if they have 0
2927 // opacity, since they can consume touches and alter the effects of the
2928 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002929 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002930 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2931 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002932 } else if (info->ownerUid == otherInfo->ownerUid) {
2933 // If ownerUid is the same we don't generate occlusion events as there
2934 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002935 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002936 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002937 return false;
2938 } else if (otherInfo->displayId != info->displayId) {
2939 return false;
2940 }
2941 return true;
2942}
2943
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002944/**
2945 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2946 * untrusted, one should check:
2947 *
2948 * 1. If result.hasBlockingOcclusion is true.
2949 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2950 * BLOCK_UNTRUSTED.
2951 *
2952 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2953 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2954 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2955 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2956 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2957 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2958 *
2959 * If neither of those is true, then it means the touch can be allowed.
2960 */
2961InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002962 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2963 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002964 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002965 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002966 TouchOcclusionInfo info;
2967 info.hasBlockingOcclusion = false;
2968 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002969 info.obscuringUid = gui::Uid::INVALID;
2970 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002971 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002972 if (windowHandle == otherHandle) {
2973 break; // All future windows are below us. Exit early.
2974 }
chaviw98318de2021-05-19 16:45:23 -05002975 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002976 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2977 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002978 if (DEBUG_TOUCH_OCCLUSION) {
2979 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00002980 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002981 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002982 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2983 // we perform the checks below to see if the touch can be propagated or not based on the
2984 // window's touch occlusion mode
2985 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2986 info.hasBlockingOcclusion = true;
2987 info.obscuringUid = otherInfo->ownerUid;
2988 info.obscuringPackage = otherInfo->packageName;
2989 break;
2990 }
2991 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002992 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002993 float opacity =
2994 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2995 // Given windows A and B:
2996 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2997 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2998 opacityByUid[uid] = opacity;
2999 if (opacity > info.obscuringOpacity) {
3000 info.obscuringOpacity = opacity;
3001 info.obscuringUid = uid;
3002 info.obscuringPackage = otherInfo->packageName;
3003 }
3004 }
3005 }
3006 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003007 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003008 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003009 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003010 return info;
3011}
3012
chaviw98318de2021-05-19 16:45:23 -05003013std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003014 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003015 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003016 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3017 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3018 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003019 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003020 info->ownerUid.toString().c_str(), info->id,
3021 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3022 info->frameTop, info->frameRight, info->frameBottom,
3023 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3024 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3025 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003026 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003027}
3028
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003029bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3030 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003031 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3032 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003033 return false;
3034 }
3035 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003036 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003037 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003038 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003039 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3040 return false;
3041 }
3042 return true;
3043}
3044
chaviw98318de2021-05-19 16:45:23 -05003045bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003048 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3049 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003050 if (windowHandle == otherHandle) {
3051 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
chaviw98318de2021-05-19 16:45:23 -05003053 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003054 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003055 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 return true;
3057 }
3058 }
3059 return false;
3060}
3061
chaviw98318de2021-05-19 16:45:23 -05003062bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003063 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003064 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3065 const WindowInfo* windowInfo = windowHandle->getInfo();
3066 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003067 if (windowHandle == otherHandle) {
3068 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003069 }
chaviw98318de2021-05-19 16:45:23 -05003070 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003071 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003072 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003073 return true;
3074 }
3075 }
3076 return false;
3077}
3078
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003079std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003080 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003081 if (applicationHandle != nullptr) {
3082 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003083 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 } else {
3085 return applicationHandle->getName();
3086 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003087 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003088 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003090 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 }
3092}
3093
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003094void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003095 if (!isUserActivityEvent(eventEntry)) {
3096 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003097 return;
3098 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003099 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003100 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003101 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003102 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003103 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003104 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003105 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 }
3107 }
3108
3109 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003110 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003111 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003112 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3113 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 return;
3115 }
Josep del Riob3981622023-04-18 15:49:45 +00003116 if (windowDisablingUserActivityInfo != nullptr) {
3117 if (DEBUG_DISPATCH_CYCLE) {
3118 ALOGD("Not poking user activity: disabled by window '%s'.",
3119 windowDisablingUserActivityInfo->name.c_str());
3120 }
3121 return;
3122 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003123 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 eventType = USER_ACTIVITY_EVENT_TOUCH;
3125 }
3126 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003128 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003129 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3130 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003131 return;
3132 }
Josep del Riob3981622023-04-18 15:49:45 +00003133 // If the key code is unknown, we don't consider it user activity
3134 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3135 return;
3136 }
3137 // Don't inhibit events that were intercepted or are not passed to
3138 // the apps, like system shortcuts
3139 if (windowDisablingUserActivityInfo != nullptr &&
3140 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3141 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3142 if (DEBUG_DISPATCH_CYCLE) {
3143 ALOGD("Not poking user activity: disabled by window '%s'.",
3144 windowDisablingUserActivityInfo->name.c_str());
3145 }
3146 return;
3147 }
3148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 eventType = USER_ACTIVITY_EVENT_BUTTON;
3150 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003152 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003153 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003154 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 break;
3156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
Prabir Pradhancef936d2021-07-21 16:17:52 +00003159 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3160 REQUIRES(mLock) {
3161 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003162 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003163 };
3164 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165}
3166
3167void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003168 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003169 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003170 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003171 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003173 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003174 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003175 ATRACE_NAME(message.c_str());
3176 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003177 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003178 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003179 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003180 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003181 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003182 inputTarget.getPointerInfoString().c_str());
3183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
3185 // Skip this event if the connection status is not normal.
3186 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003187 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003188 if (DEBUG_DISPATCH_CYCLE) {
3189 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003190 connection->getInputChannelName().c_str(),
3191 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193 return;
3194 }
3195
3196 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003197 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003198 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003200 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003202 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003203 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003204 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3205 logDispatchStateLocked();
3206 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3207 "target on connection "
3208 << connection->getInputChannelName() << " for "
3209 << originalMotionEntry.getDescription();
3210 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003211 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003212 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3213 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 if (!splitMotionEntry) {
3215 return; // split event was dropped
3216 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003217 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3218 std::string reason = std::string("reason=pointer cancel on split window");
3219 android_log_event_list(LOGTAG_INPUT_CANCEL)
3220 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3221 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003222 if (DEBUG_FOCUS) {
3223 ALOGD("channel '%s' ~ Split motion event.",
3224 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003225 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003226 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003227 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3228 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 return;
3230 }
3231 }
3232
3233 // Not splitting. Enqueue dispatch entries for the event as is.
3234 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3235}
3236
3237void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003238 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003240 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003241 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003243 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003244 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003245 ATRACE_NAME(message.c_str());
3246 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003247 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3248 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003249
hongzuo liu95785e22022-09-06 02:51:35 +00003250 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
3252 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003253 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003254 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003255 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003256 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003257 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003258 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003259 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003260 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003261 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003262 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003263 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
3266 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003267 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 startDispatchCycleLocked(currentTime, connection);
3269 }
3270}
3271
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003272void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003273 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003274 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003276 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003277 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3278 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003279 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003280 ATRACE_NAME(message.c_str());
3281 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3283 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 return;
3285 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003286
3287 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3288 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
3290 // This is a new event.
3291 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003292 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003293 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003295 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3296 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003297 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003300 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003301 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3303 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003304 LOG(WARNING) << "channel " << connection->getInputChannelName()
3305 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 return; // skip the inconsistent event
3307 }
3308 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003311 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003313 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3314 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3315 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3316 static_cast<int32_t>(IdGenerator::Source::OTHER);
3317 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003318 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003320 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003324 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003326 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3328 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003329 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 }
3331 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003332 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3333 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003334 if (DEBUG_DISPATCH_CYCLE) {
3335 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3336 "enter event",
3337 connection->getInputChannelName().c_str());
3338 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003339 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3340 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003344 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3345 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3346 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003347 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3349 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003350 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3355 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003356 LOG(WARNING) << "channel " << connection->getInputChannelName()
3357 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 return; // skip the inconsistent event
3359 }
3360
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003361 dispatchEntry->resolvedEventId =
3362 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3363 ? mIdGenerator.nextId()
3364 : motionEntry.id;
3365 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3366 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3367 ") to MotionEvent(id=0x%" PRIx32 ").",
3368 motionEntry.id, dispatchEntry->resolvedEventId);
3369 ATRACE_NAME(message.c_str());
3370 }
3371
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003372 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3373 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3374 // Skip reporting pointer down outside focus to the policy.
3375 break;
3376 }
3377
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003378 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003379 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380
3381 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003383 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003384 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003385 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3386 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003387 break;
3388 }
Chris Yef59a2f42020-10-16 12:55:26 -07003389 case EventEntry::Type::SENSOR: {
3390 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3391 break;
3392 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003393 case EventEntry::Type::CONFIGURATION_CHANGED:
3394 case EventEntry::Type::DEVICE_RESET: {
3395 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003396 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003397 break;
3398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400
3401 // Remember that we are waiting for this dispatch to complete.
3402 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003403 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
3405
3406 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003407 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003408 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003409}
3410
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003411/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003412 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003413 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003414 * The first role is to log input interaction with windows, which helps determine what the user was
3415 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3416 * that user started interacting with launcher window, as well as any other window that received
3417 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3418 * when the set of tokens that received the event changes. It is not logged again as long as the
3419 * user is interacting with the same windows.
3420 *
3421 * The second role is to track input device activity for metrics collection. For each input event,
3422 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3423 * input_interaction logs, the device interaction is reported even when the set of interaction
3424 * tokens do not change.
3425 *
3426 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3427 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003428 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003429void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3430 const std::vector<InputTarget>& targets) {
3431 int32_t deviceId;
3432 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003433 // Skip ACTION_UP events, and all events other than keys and motions
3434 if (entry.type == EventEntry::Type::KEY) {
3435 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3436 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3437 return;
3438 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003439 deviceId = keyEntry.deviceId;
3440 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003441 } else if (entry.type == EventEntry::Type::MOTION) {
3442 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3443 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003444 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3445 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003446 return;
3447 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003448 deviceId = motionEntry.deviceId;
3449 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003450 } else {
3451 return; // Not a key or a motion
3452 }
3453
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003454 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003455 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003456 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003457 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003458 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 continue; // Skip windows that receive ACTION_OUTSIDE
3460 }
3461
3462 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003463 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003464 if (connection == nullptr) {
3465 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003466 }
3467 newConnectionTokens.insert(std::move(token));
3468 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003469 if (target.windowHandle) {
3470 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3471 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003472 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003473
3474 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3475 REQUIRES(mLock) {
3476 scoped_unlock unlock(mLock);
3477 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3478 };
3479 postCommandLocked(std::move(command));
3480
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003481 if (newConnectionTokens == mInteractionConnectionTokens) {
3482 return; // no change
3483 }
3484 mInteractionConnectionTokens = newConnectionTokens;
3485
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003486 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003487 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003488 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003489 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003490 std::string message = "Interaction with: " + targetList;
3491 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003492 message += "<none>";
3493 }
3494 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3495}
3496
chaviwfd6d3512019-03-25 13:23:49 -07003497void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003498 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003499 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003500 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3501 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003502 return;
3503 }
3504
Vishnu Nairc519ff72021-01-21 08:23:08 -08003505 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003506 if (focusedToken == token) {
3507 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003508 return;
3509 }
3510
Prabir Pradhancef936d2021-07-21 16:17:52 +00003511 auto command = [this, token]() REQUIRES(mLock) {
3512 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003513 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003514 };
3515 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516}
3517
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003518status_t InputDispatcher::publishMotionEvent(Connection& connection,
3519 DispatchEntry& dispatchEntry) const {
3520 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3521 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3522
3523 PointerCoords scaledCoords[MAX_POINTERS];
3524 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3525
3526 // Set the X and Y offset and X and Y scale depending on the input source.
3527 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003528 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003529 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3530 if (globalScaleFactor != 1.0f) {
3531 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3532 scaledCoords[i] = motionEntry.pointerCoords[i];
3533 // Don't apply window scale here since we don't want scale to affect raw
3534 // coordinates. The scale will be sent back to the client and applied
3535 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003536 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003537 }
3538 usingCoords = scaledCoords;
3539 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003540 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003541 // We don't want the dispatch target to know the coordinates
3542 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3543 scaledCoords[i].clear();
3544 }
3545 usingCoords = scaledCoords;
3546 }
3547
3548 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3549
3550 // Publish the motion event.
3551 return connection.inputPublisher
3552 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3553 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3554 std::move(hmac), dispatchEntry.resolvedAction,
3555 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3556 motionEntry.edgeFlags, motionEntry.metaState,
3557 motionEntry.buttonState, motionEntry.classification,
3558 dispatchEntry.transform, motionEntry.xPrecision,
3559 motionEntry.yPrecision, motionEntry.xCursorPosition,
3560 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3561 motionEntry.downTime, motionEntry.eventTime,
3562 motionEntry.pointerCount, motionEntry.pointerProperties,
3563 usingCoords);
3564}
3565
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003567 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003568 if (ATRACE_ENABLED()) {
3569 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003570 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003571 ATRACE_NAME(message.c_str());
3572 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003573 if (DEBUG_DISPATCH_CYCLE) {
3574 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003577 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003578 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003580 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003581 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582
3583 // Publish the event.
3584 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003585 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3586 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003587 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003588 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3589 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003590 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3591 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3592 << connection->getInputChannelName();
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003595 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003596 status = connection->inputPublisher
3597 .publishKeyEvent(dispatchEntry->seq,
3598 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3599 keyEntry.source, keyEntry.displayId,
3600 std::move(hmac), dispatchEntry->resolvedAction,
3601 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3602 keyEntry.scanCode, keyEntry.metaState,
3603 keyEntry.repeatCount, keyEntry.downTime,
3604 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
3607
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003608 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003609 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3610 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3611 << connection->getInputChannelName();
3612 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003613 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 break;
3615 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003616
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003617 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003618 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003619 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003620 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003621 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003622 break;
3623 }
3624
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003625 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3626 const TouchModeEntry& touchModeEntry =
3627 static_cast<const TouchModeEntry&>(eventEntry);
3628 status = connection->inputPublisher
3629 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3630 touchModeEntry.inTouchMode);
3631
3632 break;
3633 }
3634
Prabir Pradhan99987712020-11-10 18:43:05 -08003635 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3636 const auto& captureEntry =
3637 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3638 status = connection->inputPublisher
3639 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003640 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003641 break;
3642 }
3643
arthurhungb89ccb02020-12-30 16:19:01 +08003644 case EventEntry::Type::DRAG: {
3645 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3646 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3647 dragEntry.id, dragEntry.x,
3648 dragEntry.y,
3649 dragEntry.isExiting);
3650 break;
3651 }
3652
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003653 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003654 case EventEntry::Type::DEVICE_RESET:
3655 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003656 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003657 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003658 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
3662 // Check the result.
3663 if (status) {
3664 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003665 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003667 "This is unexpected because the wait queue is empty, so the pipe "
3668 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003669 "event to it, status=%s(%d)",
3670 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3671 status);
Harry Cutts33476232023-01-30 19:57:29 +00003672 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 } else {
3674 // Pipe is full and we are waiting for the app to finish process some events
3675 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003676 if (DEBUG_DISPATCH_CYCLE) {
3677 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3678 "waiting for the application to catch up",
3679 connection->getInputChannelName().c_str());
3680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682 } else {
3683 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003684 "status=%s(%d)",
3685 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3686 status);
Harry Cutts33476232023-01-30 19:57:29 +00003687 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689 return;
3690 }
3691
3692 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003693 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3694 connection->outboundQueue.end(),
3695 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003696 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003697 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003698 if (connection->responsive) {
3699 mAnrTracker.insert(dispatchEntry->timeoutTime,
3700 connection->inputChannel->getConnectionToken());
3701 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003702 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704}
3705
chaviw09c8d2d2020-08-24 15:48:26 -07003706std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3707 size_t size;
3708 switch (event.type) {
3709 case VerifiedInputEvent::Type::KEY: {
3710 size = sizeof(VerifiedKeyEvent);
3711 break;
3712 }
3713 case VerifiedInputEvent::Type::MOTION: {
3714 size = sizeof(VerifiedMotionEvent);
3715 break;
3716 }
3717 }
3718 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3719 return mHmacKeyManager.sign(start, size);
3720}
3721
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003722const std::array<uint8_t, 32> InputDispatcher::getSignature(
3723 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003724 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003725 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003726 // Only sign events up and down events as the purely move events
3727 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003728 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003729 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003730
3731 VerifiedMotionEvent verifiedEvent =
3732 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3733 verifiedEvent.actionMasked = actionMasked;
3734 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3735 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003736}
3737
3738const std::array<uint8_t, 32> InputDispatcher::getSignature(
3739 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3740 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3741 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3742 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003743 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744}
3745
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003747 const std::shared_ptr<Connection>& connection,
3748 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003749 if (DEBUG_DISPATCH_CYCLE) {
3750 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3751 connection->getInputChannelName().c_str(), seq, toString(handled));
3752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003754 if (connection->status == Connection::Status::BROKEN ||
3755 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 return;
3757 }
3758
3759 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003760 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3761 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3762 };
3763 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764}
3765
3766void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003767 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003768 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003769 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003770 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3771 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773
3774 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003775 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003776 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003777 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003778 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
3780 // The connection appears to be unrecoverably broken.
3781 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003782 if (connection->status == Connection::Status::NORMAL) {
3783 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784
3785 if (notify) {
3786 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003787 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3788 connection->getInputChannelName().c_str());
3789
3790 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003791 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003792 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003793 };
3794 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
3796 }
3797}
3798
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003799void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3800 while (!queue.empty()) {
3801 DispatchEntry* dispatchEntry = queue.front();
3802 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003803 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805}
3806
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003807void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003809 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811 delete dispatchEntry;
3812}
3813
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003814int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3815 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003816 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003817 if (connection == nullptr) {
3818 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3819 connectionToken.get(), events);
3820 return 0; // remove the callback
3821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823 bool notify;
3824 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3825 if (!(events & ALOOPER_EVENT_INPUT)) {
3826 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3827 "events=0x%x",
3828 connection->getInputChannelName().c_str(), events);
3829 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003832 nsecs_t currentTime = now();
3833 bool gotOne = false;
3834 status_t status = OK;
3835 for (;;) {
3836 Result<InputPublisher::ConsumerResponse> result =
3837 connection->inputPublisher.receiveConsumerResponse();
3838 if (!result.ok()) {
3839 status = result.error().code();
3840 break;
3841 }
3842
3843 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3844 const InputPublisher::Finished& finish =
3845 std::get<InputPublisher::Finished>(*result);
3846 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3847 finish.consumeTime);
3848 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003849 if (shouldReportMetricsForConnection(*connection)) {
3850 const InputPublisher::Timeline& timeline =
3851 std::get<InputPublisher::Timeline>(*result);
3852 mLatencyTracker
3853 .trackGraphicsLatency(timeline.inputEventId,
3854 connection->inputChannel->getConnectionToken(),
3855 std::move(timeline.graphicsTimeline));
3856 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003857 }
3858 gotOne = true;
3859 }
3860 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003861 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003862 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 return 1;
3864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 }
3866
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003867 notify = status != DEAD_OBJECT || !connection->monitor;
3868 if (notify) {
3869 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3870 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3871 status);
3872 }
3873 } else {
3874 // Monitor channels are never explicitly unregistered.
3875 // We do it automatically when the remote endpoint is closed so don't warn about them.
3876 const bool stillHaveWindowHandle =
3877 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3878 notify = !connection->monitor && stillHaveWindowHandle;
3879 if (notify) {
3880 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3881 connection->getInputChannelName().c_str(), events);
3882 }
3883 }
3884
3885 // Remove the channel.
3886 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3887 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888}
3889
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003890void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003892 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003893 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 }
3895}
3896
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003897void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003898 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003899 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003900 for (const Monitor& monitor : monitors) {
3901 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003902 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003903 }
3904}
3905
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003907 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003908 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003909 if (connection == nullptr) {
3910 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003912
3913 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914}
3915
3916void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003917 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003918 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 return;
3920 }
3921
3922 nsecs_t currentTime = now();
3923
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003924 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003925 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003927 if (cancelationEvents.empty()) {
3928 return;
3929 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003930 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3931 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003932 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003933 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003934 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003935 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003936
Arthur Hungb3307ee2021-10-14 10:57:37 +00003937 std::string reason = std::string("reason=").append(options.reason);
3938 android_log_event_list(LOGTAG_INPUT_CANCEL)
3939 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3940
Svet Ganov5d3bc372020-01-26 23:11:07 -08003941 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003942 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003943 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3944 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003945 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003946 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003947 target.globalScaleFactor = windowInfo->globalScaleFactor;
3948 }
3949 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003950 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003951
hongzuo liu95785e22022-09-06 02:51:35 +00003952 const bool wasEmpty = connection->outboundQueue.empty();
3953
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003954 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003955 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003956 switch (cancelationEventEntry->type) {
3957 case EventEntry::Type::KEY: {
3958 logOutboundKeyDetails("cancel - ",
3959 static_cast<const KeyEntry&>(*cancelationEventEntry));
3960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003962 case EventEntry::Type::MOTION: {
3963 logOutboundMotionDetails("cancel - ",
3964 static_cast<const MotionEntry&>(*cancelationEventEntry));
3965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003967 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003968 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003969 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3970 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003971 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003972 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003973 break;
3974 }
3975 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003976 case EventEntry::Type::DEVICE_RESET:
3977 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003978 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003979 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003980 break;
3981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 }
3983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003984 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003985 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003987
hongzuo liu95785e22022-09-06 02:51:35 +00003988 // If the outbound queue was previously empty, start the dispatch cycle going.
3989 if (wasEmpty && !connection->outboundQueue.empty()) {
3990 startDispatchCycleLocked(currentTime, connection);
3991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992}
3993
Svet Ganov5d3bc372020-01-26 23:11:07 -08003994void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003995 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003996 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003997 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003998 return;
3999 }
4000
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004001 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004002 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004003
4004 if (downEvents.empty()) {
4005 return;
4006 }
4007
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004008 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004009 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4010 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004011 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004012
4013 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004014 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004015 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4016 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004017 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004018 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004019 target.globalScaleFactor = windowInfo->globalScaleFactor;
4020 }
4021 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004022 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004023
hongzuo liu95785e22022-09-06 02:51:35 +00004024 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004025 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026 switch (downEventEntry->type) {
4027 case EventEntry::Type::MOTION: {
4028 logOutboundMotionDetails("down - ",
4029 static_cast<const MotionEntry&>(*downEventEntry));
4030 break;
4031 }
4032
4033 case EventEntry::Type::KEY:
4034 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004035 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004037 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004038 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004039 case EventEntry::Type::SENSOR:
4040 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004041 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004042 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043 break;
4044 }
4045 }
4046
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004047 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004048 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 }
4050
hongzuo liu95785e22022-09-06 02:51:35 +00004051 // If the outbound queue was previously empty, start the dispatch cycle going.
4052 if (wasEmpty && !connection->outboundQueue.empty()) {
4053 startDispatchCycleLocked(downTime, connection);
4054 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004055}
4056
Arthur Hungc539dbb2022-12-08 07:45:36 +00004057void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4058 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4059 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004060 std::shared_ptr<Connection> wallpaperConnection =
4061 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004062 if (wallpaperConnection != nullptr) {
4063 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4064 }
4065 }
4066}
4067
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004068std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004069 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4070 nsecs_t splitDownTime) {
4071 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
4073 uint32_t splitPointerIndexMap[MAX_POINTERS];
4074 PointerProperties splitPointerProperties[MAX_POINTERS];
4075 PointerCoords splitPointerCoords[MAX_POINTERS];
4076
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004077 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 uint32_t splitPointerCount = 0;
4079
4080 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004083 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004085 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004087 splitPointerProperties[splitPointerCount] = pointerProperties;
4088 splitPointerCoords[splitPointerCount] =
4089 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 splitPointerCount += 1;
4091 }
4092 }
4093
4094 if (splitPointerCount != pointerIds.count()) {
4095 // This is bad. We are missing some of the pointers that we expected to deliver.
4096 // Most likely this indicates that we received an ACTION_MOVE events that has
4097 // different pointer ids than we expected based on the previous ACTION_DOWN
4098 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4099 // in this way.
4100 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004101 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004102 "a broken sequence of pointer ids from the input device: %s",
4103 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004104 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 }
4106
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004107 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4110 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4112 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004113 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004115 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 if (pointerIds.count() == 1) {
4117 // The first/last pointer went down/up.
4118 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004120 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4121 ? AMOTION_EVENT_ACTION_CANCEL
4122 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 } else {
4124 // A secondary pointer went down/up.
4125 uint32_t splitPointerIndex = 0;
4126 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4127 splitPointerIndex += 1;
4128 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 action = maskedAction |
4130 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 }
4132 } else {
4133 // An unrelated pointer changed.
4134 action = AMOTION_EVENT_ACTION_MOVE;
4135 }
4136 }
4137
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004138 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4139 logDispatchStateLocked();
4140 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4141 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4142 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004143 }
4144
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004145 int32_t newId = mIdGenerator.nextId();
4146 if (ATRACE_ENABLED()) {
4147 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4148 ") to MotionEvent(id=0x%" PRIx32 ").",
4149 originalMotionEntry.id, newId);
4150 ATRACE_NAME(message.c_str());
4151 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004152 std::unique_ptr<MotionEntry> splitMotionEntry =
4153 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4154 originalMotionEntry.deviceId, originalMotionEntry.source,
4155 originalMotionEntry.displayId,
4156 originalMotionEntry.policyFlags, action,
4157 originalMotionEntry.actionButton,
4158 originalMotionEntry.flags, originalMotionEntry.metaState,
4159 originalMotionEntry.buttonState,
4160 originalMotionEntry.classification,
4161 originalMotionEntry.edgeFlags,
4162 originalMotionEntry.xPrecision,
4163 originalMotionEntry.yPrecision,
4164 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004165 originalMotionEntry.yCursorPosition, splitDownTime,
4166 splitPointerCount, splitPointerProperties,
4167 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004169 if (originalMotionEntry.injectionState) {
4170 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 splitMotionEntry->injectionState->refCount += 1;
4172 }
4173
4174 return splitMotionEntry;
4175}
4176
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004177void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004178 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004179 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181
Antonio Kantekf16f2832021-09-28 04:39:20 +00004182 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004184 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004186 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004187 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004188 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 } // release lock
4190
4191 if (needWake) {
4192 mLooper->wake();
4193 }
4194}
4195
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004196/**
4197 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004198 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4199 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4200 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4201 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4202 * potentially handle the back key presses.
4203 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4204 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004205 */
4206void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004208 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4209 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004210 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004211 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004212 }
4213 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004214 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004215 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004216 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004217 keyCode = newKeyCode;
4218 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4219 }
4220 } else if (action == AKEY_EVENT_ACTION_UP) {
4221 // In order to maintain a consistent stream of up and down events, check to see if the key
4222 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4223 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004224 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004225 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004226 auto replacementIt = mReplacedKeys.find(replacement);
4227 if (replacementIt != mReplacedKeys.end()) {
4228 keyCode = replacementIt->second;
4229 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004230 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4231 }
4232 }
4233}
4234
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004235void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004236 ALOGD_IF(debugInboundEventDetails(),
4237 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4238 ", deviceId=%d, source=%s, displayId=%" PRId32
4239 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4240 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004241 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4242 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4243 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004244 Result<void> keyCheck = validateKeyEvent(args.action);
4245 if (!keyCheck.ok()) {
4246 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 return;
4248 }
4249
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004250 uint32_t policyFlags = args.policyFlags;
4251 int32_t flags = args.flags;
4252 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004253 // InputDispatcher tracks and generates key repeats on behalf of
4254 // whatever notifies it, so repeatCount should always be set to 0
4255 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4257 policyFlags |= POLICY_FLAG_VIRTUAL;
4258 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 if (policyFlags & POLICY_FLAG_FUNCTION) {
4261 metaState |= AMETA_FUNCTION_ON;
4262 }
4263
4264 policyFlags |= POLICY_FLAG_TRUSTED;
4265
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004266 int32_t keyCode = args.keyCode;
4267 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004268
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004270 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4271 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4272 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Michael Wright2b3c3302018-03-02 17:19:13 +00004274 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004275 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004276 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4277 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Antonio Kantekf16f2832021-09-28 04:39:20 +00004281 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 { // acquire lock
4283 mLock.lock();
4284
4285 if (shouldSendKeyToInputFilterLocked(args)) {
4286 mLock.unlock();
4287
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004288 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004289 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 return; // event was consumed by the filter
4291 }
4292
4293 mLock.lock();
4294 }
4295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004296 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004297 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4298 args.displayId, policyFlags, args.action, flags, keyCode,
4299 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004301 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 mLock.unlock();
4303 } // release lock
4304
4305 if (needWake) {
4306 mLooper->wake();
4307 }
4308}
4309
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004310bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 return mInputFilterEnabled;
4312}
4313
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004314void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004315 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004316 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004318 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4320 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004321 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4322 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4323 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4324 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4325 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004326 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004327 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4328 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004329 i, args.pointerProperties[i].id,
4330 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4331 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4332 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4333 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4334 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4335 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4336 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4337 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4338 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4339 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004342
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004343 Result<void> motionCheck =
4344 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4345 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004346 if (!motionCheck.ok()) {
4347 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4348 return;
4349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004351 if (DEBUG_VERIFY_EVENTS) {
4352 auto [it, _] =
4353 mVerifiersByDisplay.try_emplace(args.displayId,
4354 StringPrintf("display %" PRId32, args.displayId));
4355 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004356 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4357 args.pointerProperties.data(), args.pointerCoords.data(),
4358 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004359 if (!result.ok()) {
4360 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4361 }
4362 }
4363
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004364 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004366
4367 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004368 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004369 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4370 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Antonio Kantekf16f2832021-09-28 04:39:20 +00004374 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 { // acquire lock
4376 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004377 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4378 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4379 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004380 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004381 if (touchStateIt != mTouchStatesByDisplay.end()) {
4382 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004383 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004384 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4385 }
4386 }
4387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388
4389 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004390 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004392 displayTransform = it->second.transform;
4393 }
4394
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 mLock.unlock();
4396
4397 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004398 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4399 args.action, args.actionButton, args.flags, args.edgeFlags,
4400 args.metaState, args.buttonState, args.classification,
4401 displayTransform, args.xPrecision, args.yPrecision,
4402 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004403 args.downTime, args.eventTime, args.getPointerCount(),
4404 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
4406 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004407 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 return; // event was consumed by the filter
4409 }
4410
4411 mLock.lock();
4412 }
4413
4414 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004415 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004416 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4417 args.displayId, policyFlags, args.action,
4418 args.actionButton, args.flags, args.metaState,
4419 args.buttonState, args.classification, args.edgeFlags,
4420 args.xPrecision, args.yPrecision,
4421 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004422 args.downTime, args.getPointerCount(),
4423 args.pointerProperties.data(),
4424 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004426 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4427 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004428 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004429 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4430 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004431 }
4432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004433 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 mLock.unlock();
4435 } // release lock
4436
4437 if (needWake) {
4438 mLooper->wake();
4439 }
4440}
4441
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004442void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004443 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4445 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004446 args.id, args.eventTime, args.deviceId, args.source,
4447 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004448 }
Chris Yef59a2f42020-10-16 12:55:26 -07004449
Antonio Kantekf16f2832021-09-28 04:39:20 +00004450 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004451 { // acquire lock
4452 mLock.lock();
4453
4454 // Just enqueue a new sensor event.
4455 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004456 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4457 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4458 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004459
4460 needWake = enqueueInboundEventLocked(std::move(newEntry));
4461 mLock.unlock();
4462 } // release lock
4463
4464 if (needWake) {
4465 mLooper->wake();
4466 }
4467}
4468
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004469void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004470 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004471 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4472 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004473 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004474 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004475}
4476
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004477bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004478 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479}
4480
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004482 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004483 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4484 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004485 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004490 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491}
4492
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004493void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004494 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004495 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4496 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498
Antonio Kantekf16f2832021-09-28 04:39:20 +00004499 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004501 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004503 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004504 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004505 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004506
4507 for (auto& [_, verifier] : mVerifiersByDisplay) {
4508 verifier.resetDevice(args.deviceId);
4509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 } // release lock
4511
4512 if (needWake) {
4513 mLooper->wake();
4514 }
4515}
4516
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004517void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004518 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004519 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4520 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004521 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004522
Antonio Kantekf16f2832021-09-28 04:39:20 +00004523 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004524 { // acquire lock
4525 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004526 auto entry =
4527 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004528 needWake = enqueueInboundEventLocked(std::move(entry));
4529 } // release lock
4530
4531 if (needWake) {
4532 mLooper->wake();
4533 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004534}
4535
Prabir Pradhan5735a322022-04-11 17:23:34 +00004536InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004537 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004538 InputEventInjectionSync syncMode,
4539 std::chrono::milliseconds timeout,
4540 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004541 Result<void> eventValidation = validateInputEvent(*event);
4542 if (!eventValidation.ok()) {
4543 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4544 return InputEventInjectionResult::FAILED;
4545 }
4546
Prabir Pradhan65613802023-02-22 23:36:58 +00004547 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004548 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004549 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4550 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4551 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004552 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004553 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
Prabir Pradhan5735a322022-04-11 17:23:34 +00004555 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004557 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004558 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4559 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4560 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4561 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4562 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004563 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004564 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004565 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004566 }
4567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004568 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004570 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004571 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004572 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004573 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004574 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4575 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4576 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004577 int32_t keyCode = incomingKey.getKeyCode();
4578 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004579 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004581 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004582 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004583 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4584 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4585 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4588 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004589 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590
4591 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4592 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004593 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4595 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4596 std::to_string(t.duration().count()).c_str());
4597 }
4598 }
4599
4600 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004601 std::unique_ptr<KeyEntry> injectedEntry =
4602 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004603 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004604 incomingKey.getDisplayId(), policyFlags, action,
4605 flags, keyCode, incomingKey.getScanCode(), metaState,
4606 incomingKey.getRepeatCount(),
4607 incomingKey.getDownTime());
4608 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004609 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 }
4611
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004612 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004613 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004614 const bool isPointerEvent =
4615 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4616 // If a pointer event has no displayId specified, inject it to the default display.
4617 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4618 ? ADISPLAY_ID_DEFAULT
4619 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004620 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621
4622 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004623 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004624 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004625 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004626 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4627 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4628 std::to_string(t.duration().count()).c_str());
4629 }
4630 }
4631
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004632 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4633 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4634 }
4635
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004636 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004637 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4638 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004639 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004640 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4641 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004642 displayId, policyFlags, motionEvent.getAction(),
4643 motionEvent.getActionButton(), flags,
4644 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004645 motionEvent.getButtonState(),
4646 motionEvent.getClassification(),
4647 motionEvent.getEdgeFlags(),
4648 motionEvent.getXPrecision(),
4649 motionEvent.getYPrecision(),
4650 motionEvent.getRawXCursorPosition(),
4651 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004652 motionEvent.getDownTime(),
4653 motionEvent.getPointerCount(),
4654 motionEvent.getPointerProperties(),
4655 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004656 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004657 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004658 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004659 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004660 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004661 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004662 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4663 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004664 displayId, policyFlags,
4665 motionEvent.getAction(),
4666 motionEvent.getActionButton(), flags,
4667 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004668 motionEvent.getButtonState(),
4669 motionEvent.getClassification(),
4670 motionEvent.getEdgeFlags(),
4671 motionEvent.getXPrecision(),
4672 motionEvent.getYPrecision(),
4673 motionEvent.getRawXCursorPosition(),
4674 motionEvent.getRawYCursorPosition(),
4675 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004676 motionEvent.getPointerCount(),
4677 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004678 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004679 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4680 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004681 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004682 }
4683 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004686 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004687 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004688 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 }
4690
Prabir Pradhan5735a322022-04-11 17:23:34 +00004691 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 injectionState->injectionIsAsync = true;
4694 }
4695
4696 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004697 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698
4699 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004700 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004701 if (DEBUG_INJECTION) {
4702 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4703 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004704 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004705 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 }
4707
4708 mLock.unlock();
4709
4710 if (needWake) {
4711 mLooper->wake();
4712 }
4713
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004714 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004716 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004718 if (syncMode == InputEventInjectionSync::NONE) {
4719 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 } else {
4721 for (;;) {
4722 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004723 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 break;
4725 }
4726
4727 nsecs_t remainingTimeout = endTime - now();
4728 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004729 if (DEBUG_INJECTION) {
4730 ALOGD("injectInputEvent - Timed out waiting for injection result "
4731 "to become available.");
4732 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004733 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 break;
4735 }
4736
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004737 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 }
4739
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004740 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4741 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004743 if (DEBUG_INJECTION) {
4744 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4745 injectionState->pendingForegroundDispatches);
4746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 nsecs_t remainingTimeout = endTime - now();
4748 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004749 if (DEBUG_INJECTION) {
4750 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4751 "dispatches to finish.");
4752 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 break;
4755 }
4756
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004757 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 }
4759 }
4760 }
4761
4762 injectionState->release();
4763 } // release lock
4764
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004765 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004766 LOG(DEBUG) << "injectInputEvent - Finished with result "
4767 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769
4770 return injectionResult;
4771}
4772
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004773std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004774 std::array<uint8_t, 32> calculatedHmac;
4775 std::unique_ptr<VerifiedInputEvent> result;
4776 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004777 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004778 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4779 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4780 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004781 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004782 break;
4783 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004784 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004785 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4786 VerifiedMotionEvent verifiedMotionEvent =
4787 verifiedMotionEventFromMotionEvent(motionEvent);
4788 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004789 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004790 break;
4791 }
4792 default: {
4793 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4794 return nullptr;
4795 }
4796 }
4797 if (calculatedHmac == INVALID_HMAC) {
4798 return nullptr;
4799 }
tyiu1573a672023-02-21 22:38:32 +00004800 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004801 return nullptr;
4802 }
4803 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004804}
4805
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004806void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004807 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004808 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004810 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004811 LOG(DEBUG) << "Setting input event injection result to "
4812 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004815 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 // Log the outcome since the injector did not wait for the injection result.
4817 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004818 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004819 ALOGV("Asynchronous input event injection succeeded.");
4820 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004821 case InputEventInjectionResult::TARGET_MISMATCH:
4822 ALOGV("Asynchronous input event injection target mismatch.");
4823 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004824 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 ALOGW("Asynchronous input event injection failed.");
4826 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004827 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004828 ALOGW("Asynchronous input event injection timed out.");
4829 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004830 case InputEventInjectionResult::PENDING:
4831 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4832 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
4834 }
4835
4836 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004837 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839}
4840
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004841void InputDispatcher::transformMotionEntryForInjectionLocked(
4842 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004843 // Input injection works in the logical display coordinate space, but the input pipeline works
4844 // display space, so we need to transform the injected events accordingly.
4845 const auto it = mDisplayInfos.find(entry.displayId);
4846 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004847 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004848
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004849 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4850 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4851 const vec2 cursor =
4852 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4853 {entry.xCursorPosition, entry.yCursorPosition});
4854 entry.xCursorPosition = cursor.x;
4855 entry.yCursorPosition = cursor.y;
4856 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004857 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004858 entry.pointerCoords[i] =
4859 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4860 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004861 }
4862}
4863
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004864void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4865 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 if (injectionState) {
4867 injectionState->pendingForegroundDispatches += 1;
4868 }
4869}
4870
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004871void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4872 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 if (injectionState) {
4874 injectionState->pendingForegroundDispatches -= 1;
4875
4876 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004877 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879 }
4880}
4881
chaviw98318de2021-05-19 16:45:23 -05004882const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004883 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004884 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004885 auto it = mWindowHandlesByDisplay.find(displayId);
4886 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004887}
4888
chaviw98318de2021-05-19 16:45:23 -05004889sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004890 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004891 if (windowHandleToken == nullptr) {
4892 return nullptr;
4893 }
4894
Arthur Hungb92218b2018-08-14 12:00:21 +08004895 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004896 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4897 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004898 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004899 return windowHandle;
4900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004903 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904}
4905
chaviw98318de2021-05-19 16:45:23 -05004906sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4907 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004908 if (windowHandleToken == nullptr) {
4909 return nullptr;
4910 }
4911
chaviw98318de2021-05-19 16:45:23 -05004912 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004913 if (windowHandle->getToken() == windowHandleToken) {
4914 return windowHandle;
4915 }
4916 }
4917 return nullptr;
4918}
4919
chaviw98318de2021-05-19 16:45:23 -05004920sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4921 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004922 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004923 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4924 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004925 if (handle->getId() == windowHandle->getId() &&
4926 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004927 if (windowHandle->getInfo()->displayId != it.first) {
4928 ALOGE("Found window %s in display %" PRId32
4929 ", but it should belong to display %" PRId32,
4930 windowHandle->getName().c_str(), it.first,
4931 windowHandle->getInfo()->displayId);
4932 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004933 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 }
4936 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004937 return nullptr;
4938}
4939
chaviw98318de2021-05-19 16:45:23 -05004940sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004941 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4942 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943}
4944
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004945ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4946 auto displayInfoIt = mDisplayInfos.find(displayId);
4947 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4948 : kIdentityTransform;
4949}
4950
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004951bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4952 const MotionEntry& motionEntry) const {
4953 const WindowInfo& info = *window->getInfo();
4954
4955 // Skip spy window targets that are not valid for targeted injection.
4956 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004957 return false;
4958 }
4959
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004960 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4961 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4962 return false;
4963 }
4964
4965 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4966 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4967 window->getName().c_str());
4968 return false;
4969 }
4970
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004971 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004972 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004973 ALOGW("Not sending touch to %s because there's no corresponding connection",
4974 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004975 return false;
4976 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004977
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004978 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004979 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004980 return false;
4981 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004982
4983 // Drop events that can't be trusted due to occlusion
4984 const auto [x, y] = resolveTouchedPosition(motionEntry);
4985 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4986 if (!isTouchTrustedLocked(occlusionInfo)) {
4987 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004988 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004989 for (const auto& log : occlusionInfo.debugInfo) {
4990 ALOGD("%s", log.c_str());
4991 }
4992 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004993 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4994 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004995 return false;
4996 }
4997
4998 // Drop touch events if requested by input feature
4999 if (shouldDropInput(motionEntry, window)) {
5000 return false;
5001 }
5002
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005003 return true;
5004}
5005
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005006std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5007 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005008 auto connectionIt = mConnectionsByToken.find(token);
5009 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005010 return nullptr;
5011 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005012 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005013}
5014
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005015void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005016 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5017 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005018 // Remove all handles on a display if there are no windows left.
5019 mWindowHandlesByDisplay.erase(displayId);
5020 return;
5021 }
5022
5023 // Since we compare the pointer of input window handles across window updates, we need
5024 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005025 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5026 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5027 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005028 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005029 }
5030
chaviw98318de2021-05-19 16:45:23 -05005031 std::vector<sp<WindowInfoHandle>> newHandles;
5032 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005033 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005034 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005035 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005036 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005037 const bool canReceiveInput =
5038 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5039 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005040 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005041 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005042 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005043 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005044 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005045 }
5046
5047 if (info->displayId != displayId) {
5048 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5049 handle->getName().c_str(), displayId, info->displayId);
5050 continue;
5051 }
5052
Robert Carredd13602020-04-13 17:24:34 -07005053 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5054 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005055 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005056 oldHandle->updateFrom(handle);
5057 newHandles.push_back(oldHandle);
5058 } else {
5059 newHandles.push_back(handle);
5060 }
5061 }
5062
5063 // Insert or replace
5064 mWindowHandlesByDisplay[displayId] = newHandles;
5065}
5066
Arthur Hung72d8dc32020-03-28 00:48:39 +00005067void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005068 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005069 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005070 { // acquire lock
5071 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005072 for (const auto& [displayId, handles] : handlesPerDisplay) {
5073 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005074 }
5075 }
5076 // Wake up poll loop since it may need to make new input dispatching choices.
5077 mLooper->wake();
5078}
5079
Arthur Hungb92218b2018-08-14 12:00:21 +08005080/**
5081 * Called from InputManagerService, update window handle list by displayId that can receive input.
5082 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5083 * If set an empty list, remove all handles from the specific display.
5084 * For focused handle, check if need to change and send a cancel event to previous one.
5085 * For removed handle, check if need to send a cancel event if already in touch.
5086 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005087void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005088 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005089 if (DEBUG_FOCUS) {
5090 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005091 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005092 windowList += iwh->getName() + " ";
5093 }
5094 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096
Prabir Pradhand65552b2021-10-07 11:23:50 -07005097 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005098 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005099 const WindowInfo& info = *window->getInfo();
5100
5101 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005102 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005103 if (noInputWindow && window->getToken() != nullptr) {
5104 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5105 window->getName().c_str());
5106 window->releaseChannel();
5107 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005108
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005109 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005110 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5111 !info.inputConfig.test(
5112 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005113 "%s has feature SPY, but is not a trusted overlay.",
5114 window->getName().c_str());
5115
Prabir Pradhand65552b2021-10-07 11:23:50 -07005116 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005117 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5118 !info.inputConfig.test(
5119 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005120 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5121 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005122 }
5123
Arthur Hung72d8dc32020-03-28 00:48:39 +00005124 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005125 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126
chaviw98318de2021-05-19 16:45:23 -05005127 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005128
chaviw98318de2021-05-19 16:45:23 -05005129 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005130
Vishnu Nairc519ff72021-01-21 08:23:08 -08005131 std::optional<FocusResolver::FocusChanges> changes =
5132 mFocusResolver.setInputWindows(displayId, windowHandles);
5133 if (changes) {
5134 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005137 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5138 mTouchStatesByDisplay.find(displayId);
5139 if (stateIt != mTouchStatesByDisplay.end()) {
5140 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005141 for (size_t i = 0; i < state.windows.size();) {
5142 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005143 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005144 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005145 ALOGD("Touched window was removed: %s in display %" PRId32,
5146 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005147 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005148 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005149 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5150 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005151 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005152 "touched window was removed");
5153 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005154 // Since we are about to drop the touch, cancel the events for the wallpaper as
5155 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005156 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005157 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5158 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005159 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005160 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005163 state.windows.erase(state.windows.begin() + i);
5164 } else {
5165 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167 }
arthurhungb89ccb02020-12-30 16:19:01 +08005168
arthurhung6d4bed92021-03-17 11:59:33 +08005169 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005170 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005171 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005172 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005173 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005174 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5175 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005176 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005177 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005178 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005179
Arthur Hung72d8dc32020-03-28 00:48:39 +00005180 // Release information for windows that are no longer present.
5181 // This ensures that unused input channels are released promptly.
5182 // Otherwise, they might stick around until the window handle is destroyed
5183 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005184 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005185 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005186 if (DEBUG_FOCUS) {
5187 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005188 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005189 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005190 }
chaviw291d88a2019-02-14 10:33:58 -08005191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192}
5193
5194void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005195 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005196 if (DEBUG_FOCUS) {
5197 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5198 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5199 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005200 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005201 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005202 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 } // release lock
5204
5205 // Wake up poll loop since it may need to make new input dispatching choices.
5206 mLooper->wake();
5207}
5208
Vishnu Nair599f1412021-06-21 10:39:58 -07005209void InputDispatcher::setFocusedApplicationLocked(
5210 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5211 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5212 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5213
5214 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5215 return; // This application is already focused. No need to wake up or change anything.
5216 }
5217
5218 // Set the new application handle.
5219 if (inputApplicationHandle != nullptr) {
5220 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5221 } else {
5222 mFocusedApplicationHandlesByDisplay.erase(displayId);
5223 }
5224
5225 // No matter what the old focused application was, stop waiting on it because it is
5226 // no longer focused.
5227 resetNoFocusedWindowTimeoutLocked();
5228}
5229
Tiger Huang721e26f2018-07-24 22:26:19 +08005230/**
5231 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5232 * the display not specified.
5233 *
5234 * We track any unreleased events for each window. If a window loses the ability to receive the
5235 * released event, we will send a cancel event to it. So when the focused display is changed, we
5236 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5237 * display. The display-specified events won't be affected.
5238 */
5239void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005240 if (DEBUG_FOCUS) {
5241 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5242 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005243 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005244 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005245
5246 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005247 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005248 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005249 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005250 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005251 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005252 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005253 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005254 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005255 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005256 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005257 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5258 }
5259 }
5260 mFocusedDisplayId = displayId;
5261
Chris Ye3c2d6f52020-08-09 10:39:48 -07005262 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005263 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005264 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005265
Vishnu Nairad321cd2020-08-20 16:40:21 -07005266 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005268 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005269 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005270 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005271 }
5272 }
5273 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005274 } // release lock
5275
5276 // Wake up poll loop since it may need to make new input dispatching choices.
5277 mLooper->wake();
5278}
5279
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005281 if (DEBUG_FOCUS) {
5282 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
5285 bool changed;
5286 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005287 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288
5289 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5290 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005291 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 }
5293
5294 if (mDispatchEnabled && !enabled) {
5295 resetAndDropEverythingLocked("dispatcher is being disabled");
5296 }
5297
5298 mDispatchEnabled = enabled;
5299 mDispatchFrozen = frozen;
5300 changed = true;
5301 } else {
5302 changed = false;
5303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 } // release lock
5305
5306 if (changed) {
5307 // Wake up poll loop since it may need to make new input dispatching choices.
5308 mLooper->wake();
5309 }
5310}
5311
5312void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005313 if (DEBUG_FOCUS) {
5314 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
5317 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005318 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319
5320 if (mInputFilterEnabled == enabled) {
5321 return;
5322 }
5323
5324 mInputFilterEnabled = enabled;
5325 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5326 } // release lock
5327
5328 // Wake up poll loop since there might be work to do to drop everything.
5329 mLooper->wake();
5330}
5331
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005332bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005333 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005334 bool needWake = false;
5335 {
5336 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005337 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005338 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005339 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005340 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5341 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005342 mTouchModePerDisplay.count(displayId) == 0
5343 ? "not set"
5344 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5345
Antonio Kantek15beb512022-06-13 22:35:41 +00005346 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5347 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005348 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005349 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005350 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005351 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5352 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005353 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005354 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005355 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005356 return false;
5357 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005358 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005359 mTouchModePerDisplay[displayId] = inTouchMode;
5360 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5361 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005362 needWake = enqueueInboundEventLocked(std::move(entry));
5363 } // release lock
5364
5365 if (needWake) {
5366 mLooper->wake();
5367 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005368 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005369}
5370
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005371bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005372 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5373 if (focusedToken == nullptr) {
5374 return false;
5375 }
5376 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5377 return isWindowOwnedBy(windowHandle, pid, uid);
5378}
5379
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005380bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005381 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5382 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5383 const sp<WindowInfoHandle> windowHandle =
5384 getWindowHandleLocked(connectionToken);
5385 return isWindowOwnedBy(windowHandle, pid, uid);
5386 }) != mInteractionConnectionTokens.end();
5387}
5388
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005389void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5390 if (opacity < 0 || opacity > 1) {
5391 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5392 return;
5393 }
5394
5395 std::scoped_lock lock(mLock);
5396 mMaximumObscuringOpacityForTouch = opacity;
5397}
5398
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005399std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5400InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005401 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5402 for (TouchedWindow& w : state.windows) {
5403 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005404 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005405 }
5406 }
5407 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005408 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005409}
5410
arthurhungb89ccb02020-12-30 16:19:01 +08005411bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5412 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005413 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005414 if (DEBUG_FOCUS) {
5415 ALOGD("Trivial transfer to same window.");
5416 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005417 return true;
5418 }
5419
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422
Arthur Hungabbb9d82021-09-01 14:52:30 +00005423 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005424 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005425
Arthur Hungabbb9d82021-09-01 14:52:30 +00005426 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005427 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 return false;
5429 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005430 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5431 if (deviceIds.size() != 1) {
5432 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5433 << " for window: " << touchedWindow->dump();
5434 return false;
5435 }
5436 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005437
Arthur Hungabbb9d82021-09-01 14:52:30 +00005438 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5439 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005440 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005441 return false;
5442 }
5443
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005444 if (DEBUG_FOCUS) {
5445 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005446 touchedWindow->windowHandle->getName().c_str(),
5447 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
Arthur Hungabbb9d82021-09-01 14:52:30 +00005450 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005451 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005452 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005453 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005454 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Arthur Hungabbb9d82021-09-01 14:52:30 +00005456 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005457 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005458 ftl::Flags<InputTarget::Flags> newTargetFlags =
5459 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005460 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005461 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005462 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005463 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5464 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465
Arthur Hungabbb9d82021-09-01 14:52:30 +00005466 // Store the dragging window.
5467 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005468 if (pointerIds.count() != 1) {
5469 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5470 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005471 return false;
5472 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005473 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005474 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005475 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477
Arthur Hungabbb9d82021-09-01 14:52:30 +00005478 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005479 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5480 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005481 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005482 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005483 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5484 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005486 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5487 newTargetFlags);
5488
5489 // Check if the wallpaper window should deliver the corresponding event.
5490 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005491 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 } // release lock
5494
5495 // Wake up poll loop since it may need to make new input dispatching choices.
5496 mLooper->wake();
5497 return true;
5498}
5499
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005500/**
5501 * Get the touched foreground window on the given display.
5502 * Return null if there are no windows touched on that display, or if more than one foreground
5503 * window is being touched.
5504 */
5505sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5506 auto stateIt = mTouchStatesByDisplay.find(displayId);
5507 if (stateIt == mTouchStatesByDisplay.end()) {
5508 ALOGI("No touch state on display %" PRId32, displayId);
5509 return nullptr;
5510 }
5511
5512 const TouchState& state = stateIt->second;
5513 sp<WindowInfoHandle> touchedForegroundWindow;
5514 // If multiple foreground windows are touched, return nullptr
5515 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005516 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005517 if (touchedForegroundWindow != nullptr) {
5518 ALOGI("Two or more foreground windows: %s and %s",
5519 touchedForegroundWindow->getName().c_str(),
5520 window.windowHandle->getName().c_str());
5521 return nullptr;
5522 }
5523 touchedForegroundWindow = window.windowHandle;
5524 }
5525 }
5526 return touchedForegroundWindow;
5527}
5528
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005529// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005530bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005531 sp<IBinder> fromToken;
5532 { // acquire lock
5533 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005534 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005535 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005536 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5537 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005538 return false;
5539 }
5540
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005541 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5542 if (from == nullptr) {
5543 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5544 return false;
5545 }
5546
5547 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005548 } // release lock
5549
5550 return transferTouchFocus(fromToken, destChannelToken);
5551}
5552
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005554 if (DEBUG_FOCUS) {
5555 ALOGD("Resetting and dropping all events (%s).", reason);
5556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557
Michael Wrightfb04fd52022-11-24 22:31:11 +00005558 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 synthesizeCancelationEventsForAllConnectionsLocked(options);
5560
5561 resetKeyRepeatLocked();
5562 releasePendingEventLocked();
5563 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005564 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005566 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005567 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005568 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569}
5570
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005571void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005572 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 dumpDispatchStateLocked(dump);
5574
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005575 std::istringstream stream(dump);
5576 std::string line;
5577
5578 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005579 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 }
5581}
5582
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005583std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005584 std::string dump;
5585
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005586 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5587 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005588
5589 std::string windowName = "None";
5590 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005591 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005592 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5593 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5594 : "token has capture without window";
5595 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005596 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005597
5598 return dump;
5599}
5600
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005601void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005602 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5603 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5604 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005605 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606
Tiger Huang721e26f2018-07-24 22:26:19 +08005607 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5608 dump += StringPrintf(INDENT "FocusedApplications:\n");
5609 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5610 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005611 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005612 const std::chrono::duration timeout =
5613 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005614 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005615 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005616 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005619 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005621
Vishnu Nairc519ff72021-01-21 08:23:08 -08005622 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005623 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005625 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005626 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005627 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005628 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5629 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 }
5631 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005632 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634
arthurhung6d4bed92021-03-17 11:59:33 +08005635 if (mDragState) {
5636 dump += StringPrintf(INDENT "DragState:\n");
5637 mDragState->dump(dump, INDENT2);
5638 }
5639
Arthur Hungb92218b2018-08-14 12:00:21 +08005640 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005641 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5642 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5643 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5644 const auto& displayInfo = it->second;
5645 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5646 displayInfo.logicalHeight);
5647 displayInfo.transform.dump(dump, "transform", INDENT4);
5648 } else {
5649 dump += INDENT2 "No DisplayInfo found!\n";
5650 }
5651
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005652 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005653 dump += INDENT2 "Windows:\n";
5654 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005655 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5656 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005658 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005659 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005660 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005661 "applicationInfo.name=%s, "
5662 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005663 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005664 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005665 windowInfo->displayId,
5666 windowInfo->inputConfig.string().c_str(),
5667 windowInfo->alpha, windowInfo->frameLeft,
5668 windowInfo->frameTop, windowInfo->frameRight,
5669 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005670 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005671 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005672 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005673 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005674 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005675 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005676 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005677 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005678 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005679 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005680 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005681 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005682 }
5683 } else {
5684 dump += INDENT2 "Windows: <none>\n";
5685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 }
5687 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005688 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 }
5690
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005691 if (!mGlobalMonitorsByDisplay.empty()) {
5692 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5693 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005694 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 }
5699
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005700 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701
5702 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005703 if (!mRecentQueue.empty()) {
5704 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005705 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005706 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005707 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005708 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 }
5710 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005711 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712 }
5713
5714 // Dump event currently being dispatched.
5715 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005716 dump += INDENT "PendingEvent:\n";
5717 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005718 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005719 dump += StringPrintf(", age=%" PRId64 "ms\n",
5720 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723 }
5724
5725 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005726 if (!mInboundQueue.empty()) {
5727 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005728 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005729 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005730 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005731 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005734 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 }
5736
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005737 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005738 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005739 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005740 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005741 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005742 }
5743 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005744 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005745 }
5746
Prabir Pradhancef936d2021-07-21 16:17:52 +00005747 if (!mCommandQueue.empty()) {
5748 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5749 } else {
5750 dump += INDENT "CommandQueue: <empty>\n";
5751 }
5752
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005753 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005754 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005755 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005756 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005757 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005758 connection->inputChannel->getFd().get(),
5759 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005760 connection->getWindowName().c_str(),
5761 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005762 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005764 if (!connection->outboundQueue.empty()) {
5765 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5766 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005767 dump += dumpQueue(connection->outboundQueue, currentTime);
5768
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005770 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 }
5772
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005773 if (!connection->waitQueue.empty()) {
5774 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5775 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005776 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005778 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 }
5780 }
5781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005782 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
5785 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005786 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5787 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005789 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 }
5791
Antonio Kantek15beb512022-06-13 22:35:41 +00005792 if (!mTouchModePerDisplay.empty()) {
5793 dump += INDENT "TouchModePerDisplay:\n";
5794 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5795 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5796 std::to_string(touchMode).c_str());
5797 }
5798 } else {
5799 dump += INDENT "TouchModePerDisplay: <none>\n";
5800 }
5801
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005802 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005803 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5804 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5805 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005806 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005807 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808}
5809
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005810void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005811 const size_t numMonitors = monitors.size();
5812 for (size_t i = 0; i < numMonitors; i++) {
5813 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005814 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005815 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5816 dump += "\n";
5817 }
5818}
5819
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005820class LooperEventCallback : public LooperCallback {
5821public:
5822 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5823 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5824
5825private:
5826 std::function<int(int events)> mCallback;
5827};
5828
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005829Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005830 if (DEBUG_CHANNEL_CREATION) {
5831 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005834 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005835 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005836 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005837
5838 if (result) {
5839 return base::Error(result) << "Failed to open input channel pair with name " << name;
5840 }
5841
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005843 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005844 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005845 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005846 std::shared_ptr<Connection> connection =
5847 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5848 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005850 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5851 ALOGE("Created a new connection, but the token %p is already known", token.get());
5852 }
5853 mConnectionsByToken.emplace(token, connection);
5854
5855 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5856 this, std::placeholders::_1, token);
5857
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005858 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5859 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 } // release lock
5861
5862 // Wake the looper because some connections have changed.
5863 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005864 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865}
5866
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005867Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005868 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005869 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005870 std::shared_ptr<InputChannel> serverChannel;
5871 std::unique_ptr<InputChannel> clientChannel;
5872 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5873 if (result) {
5874 return base::Error(result) << "Failed to open input channel pair with name " << name;
5875 }
5876
Michael Wright3dd60e22019-03-27 22:06:44 +00005877 { // acquire lock
5878 std::scoped_lock _l(mLock);
5879
5880 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005881 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5882 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005883 }
5884
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005885 std::shared_ptr<Connection> connection =
5886 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005887 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005888 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005889
5890 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5891 ALOGE("Created a new connection, but the token %p is already known", token.get());
5892 }
5893 mConnectionsByToken.emplace(token, connection);
5894 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5895 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005896
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005897 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005898
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005899 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5900 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005901 }
Garfield Tan15601662020-09-22 15:32:38 -07005902
Michael Wright3dd60e22019-03-27 22:06:44 +00005903 // Wake the looper because some connections have changed.
5904 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005905 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005906}
5907
Garfield Tan15601662020-09-22 15:32:38 -07005908status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005910 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911
Harry Cutts33476232023-01-30 19:57:29 +00005912 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 if (status) {
5914 return status;
5915 }
5916 } // release lock
5917
5918 // Wake the poll loop because removing the connection may have changed the current
5919 // synchronization state.
5920 mLooper->wake();
5921 return OK;
5922}
5923
Garfield Tan15601662020-09-22 15:32:38 -07005924status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5925 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005926 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005927 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005928 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 return BAD_VALUE;
5930 }
5931
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005932 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005933
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005935 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 }
5937
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005938 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939
5940 nsecs_t currentTime = now();
5941 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5942
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005943 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944 return OK;
5945}
5946
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005947void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005948 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5949 auto& [displayId, monitors] = *it;
5950 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5951 return monitor.inputChannel->getConnectionToken() == connectionToken;
5952 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005953
Michael Wright3dd60e22019-03-27 22:06:44 +00005954 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005955 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005956 } else {
5957 ++it;
5958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 }
5960}
5961
Michael Wright3dd60e22019-03-27 22:06:44 +00005962status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005963 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005964 return pilferPointersLocked(token);
5965}
Michael Wright3dd60e22019-03-27 22:06:44 +00005966
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005967status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005968 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5969 if (!requestingChannel) {
5970 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5971 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005972 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005973
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005974 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005975 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005976 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5977 " Ignoring.");
5978 return BAD_VALUE;
5979 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005980 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5981 if (deviceIds.size() != 1) {
5982 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5983 << " in window: " << windowPtr->dump();
5984 return BAD_VALUE;
5985 }
5986 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005987
5988 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005989 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005990 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005991 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005992 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005993 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005994 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005995 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5996 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005997 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005998 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005999 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006000 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006001 if (channel != nullptr && channel->getConnectionToken() != token) {
6002 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6003 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6004 canceledWindows += channel->getName();
6005 }
6006 }
6007 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6008 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6009 canceledWindows.c_str());
6010
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006011 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006012 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006013 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006014
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006015 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006016 return OK;
6017}
6018
Prabir Pradhan99987712020-11-10 18:43:05 -08006019void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6020 { // acquire lock
6021 std::scoped_lock _l(mLock);
6022 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006023 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006024 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6025 windowHandle != nullptr ? windowHandle->getName().c_str()
6026 : "token without window");
6027 }
6028
Vishnu Nairc519ff72021-01-21 08:23:08 -08006029 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006030 if (focusedToken != windowToken) {
6031 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6032 enabled ? "enable" : "disable");
6033 return;
6034 }
6035
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006036 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006037 ALOGW("Ignoring request to %s Pointer Capture: "
6038 "window has %s requested pointer capture.",
6039 enabled ? "enable" : "disable", enabled ? "already" : "not");
6040 return;
6041 }
6042
Christine Franksb768bb42021-11-29 12:11:31 -08006043 if (enabled) {
6044 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6045 mIneligibleDisplaysForPointerCapture.end(),
6046 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6047 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6048 return;
6049 }
6050 }
6051
Prabir Pradhan99987712020-11-10 18:43:05 -08006052 setPointerCaptureLocked(enabled);
6053 } // release lock
6054
6055 // Wake the thread to process command entries.
6056 mLooper->wake();
6057}
6058
Christine Franksb768bb42021-11-29 12:11:31 -08006059void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6060 { // acquire lock
6061 std::scoped_lock _l(mLock);
6062 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6063 if (!isEligible) {
6064 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6065 }
6066 } // release lock
6067}
6068
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006069std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006071 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006072 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006073 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006074 }
6075 }
6076 }
6077 return std::nullopt;
6078}
6079
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006080std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6081 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006082 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006083 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006084 }
6085
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006086 for (const auto& [token, connection] : mConnectionsByToken) {
6087 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006088 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 }
6090 }
Robert Carr4e670e52018-08-15 13:26:12 -07006091
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006092 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093}
6094
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006095std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006096 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006097 if (connection == nullptr) {
6098 return "<nullptr>";
6099 }
6100 return connection->getInputChannelName();
6101}
6102
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006103void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006104 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006105 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006106}
6107
Prabir Pradhancef936d2021-07-21 16:17:52 +00006108void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006109 const std::shared_ptr<Connection>& connection,
6110 uint32_t seq, bool handled,
6111 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006112 // Handle post-event policy actions.
6113 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6114 if (dispatchEntryIt == connection->waitQueue.end()) {
6115 return;
6116 }
6117 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6118 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6119 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6120 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6121 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6122 }
6123 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6124 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6125 connection->inputChannel->getConnectionToken(),
6126 dispatchEntry->deliveryTime, consumeTime, finishTime);
6127 }
6128
6129 bool restartEvent;
6130 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6131 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6132 restartEvent =
6133 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6134 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6135 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6136 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6137 handled);
6138 } else {
6139 restartEvent = false;
6140 }
6141
6142 // Dequeue the event and start the next cycle.
6143 // Because the lock might have been released, it is possible that the
6144 // contents of the wait queue to have been drained, so we need to double-check
6145 // a few things.
6146 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6147 if (dispatchEntryIt != connection->waitQueue.end()) {
6148 dispatchEntry = *dispatchEntryIt;
6149 connection->waitQueue.erase(dispatchEntryIt);
6150 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6151 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6152 if (!connection->responsive) {
6153 connection->responsive = isConnectionResponsive(*connection);
6154 if (connection->responsive) {
6155 // The connection was unresponsive, and now it's responsive.
6156 processConnectionResponsiveLocked(*connection);
6157 }
6158 }
6159 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006160 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006161 connection->outboundQueue.push_front(dispatchEntry);
6162 traceOutboundQueueLength(*connection);
6163 } else {
6164 releaseDispatchEntry(dispatchEntry);
6165 }
6166 }
6167
6168 // Start the next dispatch cycle for this connection.
6169 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170}
6171
Prabir Pradhancef936d2021-07-21 16:17:52 +00006172void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6173 const sp<IBinder>& newToken) {
6174 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6175 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006176 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006177 };
6178 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179}
6180
Prabir Pradhancef936d2021-07-21 16:17:52 +00006181void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6182 auto command = [this, token, x, y]() REQUIRES(mLock) {
6183 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006184 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006185 };
6186 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006187}
6188
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006189void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006190 if (connection == nullptr) {
6191 LOG_ALWAYS_FATAL("Caller must check for nullness");
6192 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006193 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6194 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006195 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006196 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006197 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006198 return;
6199 }
6200 /**
6201 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6202 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6203 * has changed. This could cause newer entries to time out before the already dispatched
6204 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6205 * processes the events linearly. So providing information about the oldest entry seems to be
6206 * most useful.
6207 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006208 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006209 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6210 std::string reason =
6211 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006212 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006213 ns2ms(currentWait),
6214 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006215 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006216 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006217
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006218 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6219
6220 // Stop waking up for events on this connection, it is already unresponsive
6221 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006222}
6223
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006224void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6225 std::string reason =
6226 StringPrintf("%s does not have a focused window", application->getName().c_str());
6227 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006228
Yabin Cui8eb9c552023-06-08 18:05:07 +00006229 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006231 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006232 };
6233 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006234}
6235
chaviw98318de2021-05-19 16:45:23 -05006236void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006237 const std::string& reason) {
6238 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6239 updateLastAnrStateLocked(windowLabel, reason);
6240}
6241
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006242void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6243 const std::string& reason) {
6244 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006245 updateLastAnrStateLocked(windowLabel, reason);
6246}
6247
6248void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6249 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006251 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 struct tm tm;
6253 localtime_r(&t, &tm);
6254 char timestr[64];
6255 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006256 mLastAnrState.clear();
6257 mLastAnrState += INDENT "ANR:\n";
6258 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006259 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6260 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006261 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262}
6263
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6265 KeyEntry& entry) {
6266 const KeyEvent event = createKeyEvent(entry);
6267 nsecs_t delay = 0;
6268 { // release lock
6269 scoped_unlock unlock(mLock);
6270 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006271 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006272 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6273 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6274 std::to_string(t.duration().count()).c_str());
6275 }
6276 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277
6278 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006279 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006281 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006283 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006284 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006286}
6287
Prabir Pradhancef936d2021-07-21 16:17:52 +00006288void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006289 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006290 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006291 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006292 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006293 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006294 };
6295 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006296}
6297
Prabir Pradhanedd96402022-02-15 01:46:16 -08006298void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006299 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006300 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006302 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006303 };
6304 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006305}
6306
6307/**
6308 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6309 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6310 * command entry to the command queue.
6311 */
6312void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6313 std::string reason) {
6314 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006315 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006316 if (connection.monitor) {
6317 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6318 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006319 pid = findMonitorPidByTokenLocked(connectionToken);
6320 } else {
6321 // The connection is a window
6322 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6323 reason.c_str());
6324 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6325 if (handle != nullptr) {
6326 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006329 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006330}
6331
6332/**
6333 * Tell the policy that a connection has become responsive so that it can stop ANR.
6334 */
6335void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6336 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006337 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006339 pid = findMonitorPidByTokenLocked(connectionToken);
6340 } else {
6341 // The connection is a window
6342 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6343 if (handle != nullptr) {
6344 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006345 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006346 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006347 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348}
6349
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006350bool InputDispatcher::afterKeyEventLockedInterruptable(
6351 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6352 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006353 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006354 if (!handled) {
6355 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006356 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006357 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006358 return false;
6359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006361 // Get the fallback key state.
6362 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006363 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006364 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006365 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006366 connection->inputState.removeFallbackKey(originalKeyCode);
6367 }
6368
6369 if (handled || !dispatchEntry->hasForegroundTarget()) {
6370 // If the application handles the original key for which we previously
6371 // generated a fallback or if the window is not a foreground window,
6372 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006373 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006374 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006375 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6376 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6377 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6378 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6379 keyEntry.policyFlags);
6380 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006381 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006382 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383
6384 mLock.unlock();
6385
Prabir Pradhana41d2442023-04-20 21:30:40 +00006386 if (const auto unhandledKeyFallback =
6387 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6388 event, keyEntry.policyFlags);
6389 unhandledKeyFallback) {
6390 event = *unhandledKeyFallback;
6391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392
6393 mLock.lock();
6394
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006395 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006396 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006397 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006398 "application handled the original non-fallback key "
6399 "or is no longer a foreground target, "
6400 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006401 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404 connection->inputState.removeFallbackKey(originalKeyCode);
6405 }
6406 } else {
6407 // If the application did not handle a non-fallback key, first check
6408 // that we are in a good state to perform unhandled key event processing
6409 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006410 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006411 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006412 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6413 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6414 "since this is not an initial down. "
6415 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6416 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6417 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006418 return false;
6419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006420
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006421 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006422 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6423 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6424 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6425 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6426 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006427 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006428
6429 mLock.unlock();
6430
Prabir Pradhana41d2442023-04-20 21:30:40 +00006431 bool fallback = false;
6432 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6433 event, keyEntry.policyFlags);
6434 fb) {
6435 fallback = true;
6436 event = *fb;
6437 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438
6439 mLock.lock();
6440
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006441 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006442 connection->inputState.removeFallbackKey(originalKeyCode);
6443 return false;
6444 }
6445
6446 // Latch the fallback keycode for this key on an initial down.
6447 // The fallback keycode cannot change at any other point in the lifecycle.
6448 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006449 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006450 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006451 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006452 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 }
6456
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006457 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006458
6459 // Cancel the fallback key if the policy decides not to send it anymore.
6460 // We will continue to dispatch the key to the policy but we will no
6461 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006462 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6463 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006464 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6465 if (fallback) {
6466 ALOGD("Unhandled key event: Policy requested to send key %d"
6467 "as a fallback for %d, but on the DOWN it had requested "
6468 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006469 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006470 } else {
6471 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6472 "but on the DOWN it had requested to send %d. "
6473 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006474 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006475 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006477
Michael Wrightfb04fd52022-11-24 22:31:11 +00006478 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006479 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006480 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006481 synthesizeCancelationEventsForConnectionLocked(connection, options);
6482
6483 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006484 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006485 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006486 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 }
6488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006489
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006490 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6491 {
6492 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006493 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006494 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006495 for (const auto& [key, value] : fallbackKeys) {
6496 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006497 }
6498 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6499 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006502
6503 if (fallback) {
6504 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006505 keyEntry.eventTime = event.getEventTime();
6506 keyEntry.deviceId = event.getDeviceId();
6507 keyEntry.source = event.getSource();
6508 keyEntry.displayId = event.getDisplayId();
6509 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006510 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006511 keyEntry.scanCode = event.getScanCode();
6512 keyEntry.metaState = event.getMetaState();
6513 keyEntry.repeatCount = event.getRepeatCount();
6514 keyEntry.downTime = event.getDownTime();
6515 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006516
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006517 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6518 ALOGD("Unhandled key event: Dispatching fallback key. "
6519 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006520 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006521 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006522 return true; // restart the event
6523 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006524 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6525 ALOGD("Unhandled key event: No fallback key.");
6526 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006527
6528 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006529 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530 }
6531 }
6532 return false;
6533}
6534
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006535bool InputDispatcher::afterMotionEventLockedInterruptable(
6536 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6537 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006538 return false;
6539}
6540
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541void InputDispatcher::traceInboundQueueLengthLocked() {
6542 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006543 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 }
6545}
6546
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006547void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 if (ATRACE_ENABLED()) {
6549 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006550 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6551 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 }
6553}
6554
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006555void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556 if (ATRACE_ENABLED()) {
6557 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006558 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6559 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560 }
6561}
6562
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006563void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006564 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006566 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567 dumpDispatchStateLocked(dump);
6568
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006569 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006570 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006571 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572 }
6573}
6574
6575void InputDispatcher::monitor() {
6576 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006577 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006579 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580}
6581
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006582/**
6583 * Wake up the dispatcher and wait until it processes all events and commands.
6584 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6585 * this method can be safely called from any thread, as long as you've ensured that
6586 * the work you are interested in completing has already been queued.
6587 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006588bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006589 /**
6590 * Timeout should represent the longest possible time that a device might spend processing
6591 * events and commands.
6592 */
6593 constexpr std::chrono::duration TIMEOUT = 100ms;
6594 std::unique_lock lock(mLock);
6595 mLooper->wake();
6596 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6597 return result == std::cv_status::no_timeout;
6598}
6599
Vishnu Naire798b472020-07-23 13:52:21 -07006600/**
6601 * Sets focus to the window identified by the token. This must be called
6602 * after updating any input window handles.
6603 *
6604 * Params:
6605 * request.token - input channel token used to identify the window that should gain focus.
6606 * request.focusedToken - the token that the caller expects currently to be focused. If the
6607 * specified token does not match the currently focused window, this request will be dropped.
6608 * If the specified focused token matches the currently focused window, the call will succeed.
6609 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6610 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6611 * when requesting the focus change. This determines which request gets
6612 * precedence if there is a focus change request from another source such as pointer down.
6613 */
Vishnu Nair958da932020-08-21 17:12:37 -07006614void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6615 { // acquire lock
6616 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006617 std::optional<FocusResolver::FocusChanges> changes =
6618 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6619 if (changes) {
6620 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006621 }
6622 } // release lock
6623 // Wake up poll loop since it may need to make new input dispatching choices.
6624 mLooper->wake();
6625}
6626
Vishnu Nairc519ff72021-01-21 08:23:08 -08006627void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6628 if (changes.oldFocus) {
6629 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006630 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006631 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006632 "focus left window");
6633 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006634 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006635 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006636 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006637 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006638 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006639 }
6640
Prabir Pradhan99987712020-11-10 18:43:05 -08006641 // If a window has pointer capture, then it must have focus. We need to ensure that this
6642 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6643 // If the window loses focus before it loses pointer capture, then the window can be in a state
6644 // where it has pointer capture but not focus, violating the contract. Therefore we must
6645 // dispatch the pointer capture event before the focus event. Since focus events are added to
6646 // the front of the queue (above), we add the pointer capture event to the front of the queue
6647 // after the focus events are added. This ensures the pointer capture event ends up at the
6648 // front.
6649 disablePointerCaptureForcedLocked();
6650
Vishnu Nairc519ff72021-01-21 08:23:08 -08006651 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006652 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006653 }
6654}
Vishnu Nair958da932020-08-21 17:12:37 -07006655
Prabir Pradhan99987712020-11-10 18:43:05 -08006656void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006657 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006658 return;
6659 }
6660
6661 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6662
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006663 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006664 setPointerCaptureLocked(false);
6665 }
6666
6667 if (!mWindowTokenWithPointerCapture) {
6668 // No need to send capture changes because no window has capture.
6669 return;
6670 }
6671
6672 if (mPendingEvent != nullptr) {
6673 // Move the pending event to the front of the queue. This will give the chance
6674 // for the pending event to be dropped if it is a captured event.
6675 mInboundQueue.push_front(mPendingEvent);
6676 mPendingEvent = nullptr;
6677 }
6678
6679 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006680 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006681 mInboundQueue.push_front(std::move(entry));
6682}
6683
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006684void InputDispatcher::setPointerCaptureLocked(bool enable) {
6685 mCurrentPointerCaptureRequest.enable = enable;
6686 mCurrentPointerCaptureRequest.seq++;
6687 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006688 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006689 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006690 };
6691 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006692}
6693
Vishnu Nair599f1412021-06-21 10:39:58 -07006694void InputDispatcher::displayRemoved(int32_t displayId) {
6695 { // acquire lock
6696 std::scoped_lock _l(mLock);
6697 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006698 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006699 setFocusedApplicationLocked(displayId, nullptr);
6700 // Call focus resolver to clean up stale requests. This must be called after input windows
6701 // have been removed for the removed display.
6702 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006703 // Reset pointer capture eligibility, regardless of previous state.
6704 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006705 // Remove the associated touch mode state.
6706 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006707 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006708 } // release lock
6709
6710 // Wake up poll loop since it may need to make new input dispatching choices.
6711 mLooper->wake();
6712}
6713
Patrick Williamsd828f302023-04-28 17:52:08 -05006714void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006715 // The listener sends the windows as a flattened array. Separate the windows by display for
6716 // more convenient parsing.
6717 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006718 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006719 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006720 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006721 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006722
6723 { // acquire lock
6724 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006725
6726 // Ensure that we have an entry created for all existing displays so that if a displayId has
6727 // no windows, we can tell that the windows were removed from the display.
6728 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6729 handlesPerDisplay[displayId];
6730 }
6731
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006732 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006733 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006734 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6735 }
6736
6737 for (const auto& [displayId, handles] : handlesPerDisplay) {
6738 setInputWindowsLocked(handles, displayId);
6739 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006740
6741 if (update.vsyncId < mWindowInfosVsyncId) {
6742 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6743 ", current update vsync id: %" PRId64,
6744 mWindowInfosVsyncId, update.vsyncId);
6745 }
6746 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006747 }
6748 // Wake up poll loop since it may need to make new input dispatching choices.
6749 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006750}
6751
Vishnu Nair062a8672021-09-03 16:07:44 -07006752bool InputDispatcher::shouldDropInput(
6753 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006754 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6755 (windowHandle->getInfo()->inputConfig.test(
6756 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006757 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006758 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6759 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006760 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006761 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006762 windowHandle->getInfo()->displayId);
6763 return true;
6764 }
6765 return false;
6766}
6767
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006768void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006769 const gui::WindowInfosUpdate& update) {
6770 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006771}
6772
Arthur Hungdfd528e2021-12-08 13:23:04 +00006773void InputDispatcher::cancelCurrentTouch() {
6774 {
6775 std::scoped_lock _l(mLock);
6776 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006777 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006778 "cancel current touch");
6779 synthesizeCancelationEventsForAllConnectionsLocked(options);
6780
6781 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006782 }
6783 // Wake up poll loop since there might be work to do.
6784 mLooper->wake();
6785}
6786
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006787void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6788 std::scoped_lock _l(mLock);
6789 mMonitorDispatchingTimeout = timeout;
6790}
6791
Arthur Hungc539dbb2022-12-08 07:45:36 +00006792void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6793 const sp<WindowInfoHandle>& oldWindowHandle,
6794 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006795 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006796 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006797 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6798 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006799 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6800 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6801 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6802 newWindowHandle->getInfo()->inputConfig.test(
6803 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6804 const sp<WindowInfoHandle> oldWallpaper =
6805 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6806 const sp<WindowInfoHandle> newWallpaper =
6807 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6808 if (oldWallpaper == newWallpaper) {
6809 return;
6810 }
6811
6812 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006813 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6814 addWindowTargetLocked(oldWallpaper,
6815 oldTouchedWindow.targetFlags |
6816 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006817 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6818 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006819 }
6820
6821 if (newWallpaper != nullptr) {
6822 state.addOrUpdateWindow(newWallpaper,
6823 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6824 InputTarget::Flags::WINDOW_IS_OBSCURED |
6825 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006826 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006827 }
6828}
6829
6830void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6831 ftl::Flags<InputTarget::Flags> newTargetFlags,
6832 const sp<WindowInfoHandle> fromWindowHandle,
6833 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006834 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006835 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006836 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6837 fromWindowHandle->getInfo()->inputConfig.test(
6838 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6839 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6840 toWindowHandle->getInfo()->inputConfig.test(
6841 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6842
6843 const sp<WindowInfoHandle> oldWallpaper =
6844 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6845 const sp<WindowInfoHandle> newWallpaper =
6846 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6847 if (oldWallpaper == newWallpaper) {
6848 return;
6849 }
6850
6851 if (oldWallpaper != nullptr) {
6852 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6853 "transferring touch focus to another window");
6854 state.removeWindowByToken(oldWallpaper->getToken());
6855 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6856 }
6857
6858 if (newWallpaper != nullptr) {
6859 nsecs_t downTimeInTarget = now();
6860 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6861 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6862 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6863 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006864 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6865 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
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006899void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6900 std::scoped_lock _l(mLock);
6901
6902 mConfig.keyRepeatTimeout = timeout;
6903 mConfig.keyRepeatDelay = delay;
6904}
6905
Garfield Tane84e6f92019-08-29 17:28:41 -07006906} // namespace android::inputdispatcher