blob: 21882b5c830e6f53d9b5581989f5c047840dbfb0 [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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Vishniakou6773db62023-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 Pradhane59c6dc2023-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)) {
Daniel Norman2f99cdb2023-08-02 16:39:45 -0700671 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
672 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
673 // The Accessibility injected touch exploration event stream
674 // has known inconsistencies, so log ERROR instead of
675 // crashing the device with FATAL.
676 // TODO(b/286037469): Move a11y severity back to FATAL.
677 severity = android::base::LogSeverity::ERROR;
678 }
679 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700680 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000681 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
682 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700683 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
685 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
686 }
687 out.push_back(touchedWindow);
688 }
689 return out;
690}
691
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800692template <typename T>
693std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
694 left.insert(left.end(), right.begin(), right.end());
695 return left;
696}
697
Harry Cuttsb166c002023-05-09 13:06:05 +0000698// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
699// both.
700void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
701 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
702 if (!window.windowHandle->getInfo()->inputConfig.test(
703 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
704 // In addition to TouchState, erase this window from the input targets! We don't have a
705 // good way to do this today except by adding a nested loop.
706 // TODO(b/282025641): simplify this code once InputTargets are being identified
707 // separately from TouchedWindows.
708 std::erase_if(targets, [&](const InputTarget& target) {
709 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
710 });
711 return true;
712 }
713 return false;
714 });
715}
716
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000717} // namespace
718
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719// --- InputDispatcher ---
720
Prabir Pradhana41d2442023-04-20 21:30:40 +0000721InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800722 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
723
Prabir Pradhana41d2442023-04-20 21:30:40 +0000724InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800725 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 : mPolicy(policy),
727 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700728 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800729 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700730 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700731 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700732 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800733 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700734 mDispatchEnabled(false),
735 mDispatchFrozen(false),
736 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100737 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000738 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800739 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800740 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000741 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000742 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700743 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800744 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700746 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700747#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700748 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700749#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700750 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751}
752
753InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000754 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755
Prabir Pradhancef936d2021-07-21 16:17:52 +0000756 resetKeyRepeatLocked();
757 releasePendingEventLocked();
758 drainInboundQueueLocked();
759 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000761 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700762 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000763 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 }
765}
766
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700767status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700768 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700769 return ALREADY_EXISTS;
770 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700771 mThread = std::make_unique<InputThread>(
772 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
773 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700774}
775
776status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700777 if (mThread && mThread->isCallingThread()) {
778 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700779 return INVALID_OPERATION;
780 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700781 mThread.reset();
782 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700783}
784
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700786 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800788 std::scoped_lock _l(mLock);
789 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790
791 // Run a dispatch loop if there are no pending commands.
792 // The dispatch loop might enqueue commands to run afterwards.
793 if (!haveCommandsLocked()) {
794 dispatchOnceInnerLocked(&nextWakeupTime);
795 }
796
797 // Run all pending commands if there are any.
798 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000799 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700800 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800802
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700803 // If we are still waiting for ack on some events,
804 // we might have to wake up earlier to check if an app is anr'ing.
805 const nsecs_t nextAnrCheck = processAnrsLocked();
806 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
807
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800808 // We are about to enter an infinitely long sleep, because we have no commands or
809 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700810 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800811 mDispatcherEnteredIdle.notify_all();
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 } // release lock
814
815 // Wait for callback or timeout or wake. (make sure we round up, not down)
816 nsecs_t currentTime = now();
817 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
818 mLooper->pollOnce(timeoutMillis);
819}
820
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700821/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500822 * Raise ANR if there is no focused window.
823 * Before the ANR is raised, do a final state check:
824 * 1. The currently focused application must be the same one we are waiting for.
825 * 2. Ensure we still don't have a focused window.
826 */
827void InputDispatcher::processNoFocusedWindowAnrLocked() {
828 // Check if the application that we are waiting for is still focused.
829 std::shared_ptr<InputApplicationHandle> focusedApplication =
830 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
831 if (focusedApplication == nullptr ||
832 focusedApplication->getApplicationToken() !=
833 mAwaitedFocusedApplication->getApplicationToken()) {
834 // Unexpected because we should have reset the ANR timer when focused application changed
835 ALOGE("Waited for a focused window, but focused application has already changed to %s",
836 focusedApplication->getName().c_str());
837 return; // The focused application has changed.
838 }
839
chaviw98318de2021-05-19 16:45:23 -0500840 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500841 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
842 if (focusedWindowHandle != nullptr) {
843 return; // We now have a focused window. No need for ANR.
844 }
845 onAnrLocked(mAwaitedFocusedApplication);
846}
847
848/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700849 * Check if any of the connections' wait queues have events that are too old.
850 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
851 * Return the time at which we should wake up next.
852 */
853nsecs_t InputDispatcher::processAnrsLocked() {
854 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700855 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
857 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
858 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500859 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700860 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500861 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700862 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700863 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500864 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700865 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
866 }
867 }
868
869 // Check if any connection ANRs are due
870 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
871 if (currentTime < nextAnrCheck) { // most likely scenario
872 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
873 }
874
875 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700876 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877 if (connection == nullptr) {
878 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
879 return nextAnrCheck;
880 }
881 connection->responsive = false;
882 // Stop waking up for this unresponsive connection
883 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000884 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700885 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886}
887
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800888std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700889 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800890 if (connection->monitor) {
891 return mMonitorDispatchingTimeout;
892 }
893 const sp<WindowInfoHandle> window =
894 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500896 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700897 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500898 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899}
900
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
902 nsecs_t currentTime = now();
903
Jeff Browndc5992e2014-04-11 01:27:26 -0700904 // Reset the key repeat timer whenever normal dispatch is suspended while the
905 // device is in a non-interactive state. This is to ensure that we abort a key
906 // repeat if the device is just coming out of sleep.
907 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 resetKeyRepeatLocked();
909 }
910
911 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
912 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100913 if (DEBUG_FOCUS) {
914 ALOGD("Dispatch frozen. Waiting some more.");
915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 return;
917 }
918
919 // Optimize latency of app switches.
920 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
921 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
922 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
923 if (mAppSwitchDueTime < *nextWakeupTime) {
924 *nextWakeupTime = mAppSwitchDueTime;
925 }
926
927 // Ready to start a new event.
928 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700930 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 if (isAppSwitchDue) {
932 // The inbound queue is empty so the app switch key we were waiting
933 // for will never arrive. Stop waiting for it.
934 resetPendingAppSwitchLocked(false);
935 isAppSwitchDue = false;
936 }
937
938 // Synthesize a key repeat if appropriate.
939 if (mKeyRepeatState.lastKeyEntry) {
940 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
941 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
942 } else {
943 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
944 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
945 }
946 }
947 }
948
949 // Nothing to do if there is no pending event.
950 if (!mPendingEvent) {
951 return;
952 }
953 } else {
954 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700955 mPendingEvent = mInboundQueue.front();
956 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 traceInboundQueueLengthLocked();
958 }
959
960 // Poke user activity for this event.
961 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700962 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
965
966 // Now we have an event to dispatch.
967 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700968 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700970 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700974 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 }
976
977 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700978 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980
981 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 const ConfigurationChangedEntry& typedEntry =
984 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700986 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 break;
988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700990 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 const DeviceResetEntry& typedEntry =
992 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700994 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 break;
996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100998 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999 std::shared_ptr<FocusEntry> typedEntry =
1000 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001 dispatchFocusLocked(currentTime, typedEntry);
1002 done = true;
1003 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1004 break;
1005 }
1006
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001007 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1008 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1009 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1010 done = true;
1011 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1012 break;
1013 }
1014
Prabir Pradhan99987712020-11-10 18:43:05 -08001015 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1016 const auto typedEntry =
1017 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1018 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1019 done = true;
1020 break;
1021 }
1022
arthurhungb89ccb02020-12-30 16:19:01 +08001023 case EventEntry::Type::DRAG: {
1024 std::shared_ptr<DragEntry> typedEntry =
1025 std::static_pointer_cast<DragEntry>(mPendingEvent);
1026 dispatchDragLocked(currentTime, typedEntry);
1027 done = true;
1028 break;
1029 }
1030
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001031 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001032 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 resetPendingAppSwitchLocked(true);
1036 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001037 } else if (dropReason == DropReason::NOT_DROPPED) {
1038 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 }
1040 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001041 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001042 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001044 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1045 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001047 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048 break;
1049 }
1050
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001051 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001052 std::shared_ptr<MotionEntry> motionEntry =
1053 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001054 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1055 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001057 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001058 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001060 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1061 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001063 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
Chris Yef59a2f42020-10-16 12:55:26 -07001066
1067 case EventEntry::Type::SENSOR: {
1068 std::shared_ptr<SensorEntry> sensorEntry =
1069 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1070 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1071 dropReason = DropReason::APP_SWITCH;
1072 }
1073 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1074 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1075 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1076 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1077 dropReason = DropReason::STALE;
1078 }
1079 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1080 done = true;
1081 break;
1082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 }
1084
1085 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001087 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
Michael Wright3a981722015-06-10 15:26:13 +01001089 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
1091 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001092 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
1094}
1095
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001096bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1097 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1098}
1099
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001100/**
1101 * Return true if the events preceding this incoming motion event should be dropped
1102 * Return false otherwise (the default behaviour)
1103 */
1104bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001105 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001106 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001107
1108 // Optimize case where the current application is unresponsive and the user
1109 // decides to touch a window in a different application.
1110 // If the application takes too long to catch up then we drop all events preceding
1111 // the touch into the other window.
1112 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001113 const int32_t displayId = motionEntry.displayId;
1114 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001115 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001116
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001117 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001118 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001119 touchedWindowHandle->getApplicationToken() !=
1120 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001121 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001122 ALOGI("Pruning input queue because user touched a different application while waiting "
1123 "for %s",
1124 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001125 return true;
1126 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001127
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001128 // Alternatively, maybe there's a spy window that could handle this event.
1129 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1130 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1131 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001132 const std::shared_ptr<Connection> connection =
1133 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001134 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001135 // This spy window could take more input. Drop all events preceding this
1136 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001137 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001138 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001139 mAwaitedFocusedApplication->getName().c_str());
1140 return true;
1141 }
1142 }
1143 }
1144
1145 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1146 // yet been processed by some connections, the dispatcher will wait for these motion
1147 // events to be processed before dispatching the key event. This is because these motion events
1148 // may cause a new window to be launched, which the user might expect to receive focus.
1149 // To prevent waiting forever for such events, just send the key to the currently focused window
1150 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1151 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1152 "just send the pending key event to the focused window.");
1153 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 }
1155 return false;
1156}
1157
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001158bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001159 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 mInboundQueue.push_back(std::move(newEntry));
1161 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 traceInboundQueueLengthLocked();
1163
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001164 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001165 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001166 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1167 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 // Optimize app switch latency.
1169 // If the application takes too long to catch up then we drop all events preceding
1170 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001171 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001174 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001175 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001177 if (DEBUG_APP_SWITCH) {
1178 ALOGD("App switch is pending!");
1179 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001180 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 mAppSwitchSawKeyDown = false;
1182 needWake = true;
1183 }
1184 }
1185 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001186
1187 // If a new up event comes in, and the pending event with same key code has been asked
1188 // to try again later because of the policy. We have to reset the intercept key wake up
1189 // time for it may have been handled in the policy and could be dropped.
1190 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1191 mPendingEvent->type == EventEntry::Type::KEY) {
1192 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1193 if (pendingKey.keyCode == keyEntry.keyCode &&
1194 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001195 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1196 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001197 pendingKey.interceptKeyWakeupTime = 0;
1198 needWake = true;
1199 }
1200 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 break;
1202 }
1203
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001204 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001205 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1206 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1208 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001209 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001213 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001214 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1215 break;
1216 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001217 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001218 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001219 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001220 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001221 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1222 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001223 // nothing to do
1224 break;
1225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227
1228 return needWake;
1229}
1230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001232 // Do not store sensor event in recent queue to avoid flooding the queue.
1233 if (entry->type != EventEntry::Type::SENSOR) {
1234 mRecentQueue.push_back(entry);
1235 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001237 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 }
1239}
1240
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001241std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001242InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001243 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001245 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001246 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001247 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001248 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001249 continue;
1250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001252 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001253 if (!info.isSpy() &&
1254 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001255 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001256 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001257
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001258 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1259 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001260 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001261 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001264 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265}
1266
Prabir Pradhand65552b2021-10-07 11:23:50 -07001267std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001268 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001269 // Traverse windows from front to back and gather the touched spy windows.
1270 std::vector<sp<WindowInfoHandle>> spyWindows;
1271 const auto& windowHandles = getWindowHandlesLocked(displayId);
1272 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1273 const WindowInfo& info = *windowHandle->getInfo();
1274
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001275 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001276 continue;
1277 }
1278 if (!info.isSpy()) {
1279 // The first touched non-spy window was found, so return the spy windows touched so far.
1280 return spyWindows;
1281 }
1282 spyWindows.push_back(windowHandle);
1283 }
1284 return spyWindows;
1285}
1286
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 const char* reason;
1289 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001290 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001291 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001292 ALOGD("Dropped event because policy consumed it.");
1293 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 reason = "inbound event was dropped because the policy consumed it";
1295 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001296 case DropReason::DISABLED:
1297 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 ALOGI("Dropped event because input dispatch is disabled.");
1299 }
1300 reason = "inbound event was dropped because input dispatch is disabled";
1301 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001302 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 ALOGI("Dropped event because of pending overdue app switch.");
1304 reason = "inbound event was dropped because of pending overdue app switch";
1305 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001306 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 ALOGI("Dropped event because the current application is not responding and the user "
1308 "has started interacting with a different application.");
1309 reason = "inbound event was dropped because the current application is not responding "
1310 "and the user has started interacting with a different application";
1311 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001312 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 ALOGI("Dropped event because it is stale.");
1314 reason = "inbound event was dropped because it is stale";
1315 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 case DropReason::NO_POINTER_CAPTURE:
1317 ALOGI("Dropped event because there is no window with Pointer Capture.");
1318 reason = "inbound event was dropped because there is no window with Pointer Capture";
1319 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001320 case DropReason::NOT_DROPPED: {
1321 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 }
1325
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001327 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001328 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001332 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001333 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1334 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001335 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 synthesizeCancelationEventsForAllConnectionsLocked(options);
1337 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001338 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1339 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001340 synthesizeCancelationEventsForAllConnectionsLocked(options);
1341 }
1342 break;
1343 }
Chris Yef59a2f42020-10-16 12:55:26 -07001344 case EventEntry::Type::SENSOR: {
1345 break;
1346 }
arthurhungb89ccb02020-12-30 16:19:01 +08001347 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1348 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 break;
1350 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001351 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001352 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001353 case EventEntry::Type::CONFIGURATION_CHANGED:
1354 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001355 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001356 break;
1357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359}
1360
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001361static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1363 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364}
1365
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001366bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1367 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1368 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1369 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001372bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001373 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374}
1375
1376void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001377 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001379 if (DEBUG_APP_SWITCH) {
1380 if (handled) {
1381 ALOGD("App switch has arrived.");
1382 } else {
1383 ALOGD("App switch was abandoned.");
1384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386}
1387
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001389 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390}
1391
Prabir Pradhancef936d2021-07-21 16:17:52 +00001392bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001393 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return false;
1395 }
1396
1397 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001398 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001399 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001400 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1401 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001402 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 return true;
1404}
1405
Prabir Pradhancef936d2021-07-21 16:17:52 +00001406void InputDispatcher::postCommandLocked(Command&& command) {
1407 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408}
1409
1410void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001411 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001412 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001413 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 releaseInboundEventLocked(entry);
1415 }
1416 traceInboundQueueLengthLocked();
1417}
1418
1419void InputDispatcher::releasePendingEventLocked() {
1420 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001422 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424}
1425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001429 if (DEBUG_DISPATCH_CYCLE) {
1430 ALOGD("Injected inbound event was dropped.");
1431 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001432 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 }
1434 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 }
1437 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438}
1439
1440void InputDispatcher::resetKeyRepeatLocked() {
1441 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001442 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
1444}
1445
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1447 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
Michael Wright2e732952014-09-24 13:26:59 -07001449 uint32_t policyFlags = entry->policyFlags &
1450 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 std::shared_ptr<KeyEntry> newEntry =
1453 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1454 entry->source, entry->displayId, policyFlags, entry->action,
1455 entry->flags, entry->keyCode, entry->scanCode,
1456 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001458 newEntry->syntheticRepeat = true;
1459 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001461 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462}
1463
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001466 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1467 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469
1470 // Reset key repeating in case a keyboard device was added or removed or something.
1471 resetKeyRepeatLocked();
1472
1473 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001474 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1475 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001476 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001477 };
1478 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 return true;
1480}
1481
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1483 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001484 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1485 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1486 entry.deviceId);
1487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488
liushenxiang42232912021-05-21 20:24:09 +08001489 // Reset key repeating in case a keyboard device was disabled or enabled.
1490 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1491 resetKeyRepeatLocked();
1492 }
1493
Michael Wrightfb04fd52022-11-24 22:31:11 +00001494 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001495 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001497
1498 // Remove all active pointers from this device
1499 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1500 touchState.removeAllPointersForDevice(entry.deviceId);
1501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 return true;
1503}
1504
Vishnu Nairad321cd2020-08-20 16:40:21 -07001505void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001506 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001507 if (mPendingEvent != nullptr) {
1508 // Move the pending event to the front of the queue. This will give the chance
1509 // for the pending event to get dispatched to the newly focused window
1510 mInboundQueue.push_front(mPendingEvent);
1511 mPendingEvent = nullptr;
1512 }
1513
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 std::unique_ptr<FocusEntry> focusEntry =
1515 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1516 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001517
1518 // This event should go to the front of the queue, but behind all other focus events
1519 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001521 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 [](const std::shared_ptr<EventEntry>& event) {
1523 return event->type == EventEntry::Type::FOCUS;
1524 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001525
1526 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001528}
1529
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001530void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001531 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001532 if (channel == nullptr) {
1533 return; // Window has gone away
1534 }
1535 InputTarget target;
1536 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001537 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001538 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001539 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1540 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001541 std::string reason = std::string("reason=").append(entry->reason);
1542 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001543 dispatchEventLocked(currentTime, entry, {target});
1544}
1545
Prabir Pradhan99987712020-11-10 18:43:05 -08001546void InputDispatcher::dispatchPointerCaptureChangedLocked(
1547 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1548 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001549 dropReason = DropReason::NOT_DROPPED;
1550
Prabir Pradhan99987712020-11-10 18:43:05 -08001551 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001552 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553
1554 if (entry->pointerCaptureRequest.enable) {
1555 // Enable Pointer Capture.
1556 if (haveWindowWithPointerCapture &&
1557 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001558 // This can happen if pointer capture is disabled and re-enabled before we notify the
1559 // app of the state change, so there is no need to notify the app.
1560 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1561 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001562 }
1563 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001564 // This can happen if a window requests capture and immediately releases capture.
1565 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001566 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001567 return;
1568 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001569 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1570 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1571 return;
1572 }
1573
Vishnu Nairc519ff72021-01-21 08:23:08 -08001574 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001575 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1576 mWindowTokenWithPointerCapture = token;
1577 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001578 // Disable Pointer Capture.
1579 // We do not check if the sequence number matches for requests to disable Pointer Capture
1580 // for two reasons:
1581 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1582 // to disable capture with the same sequence number: one generated by
1583 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1584 // Capture being disabled in InputReader.
1585 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1586 // actual Pointer Capture state that affects events being generated by input devices is
1587 // in InputReader.
1588 if (!haveWindowWithPointerCapture) {
1589 // Pointer capture was already forcefully disabled because of focus change.
1590 dropReason = DropReason::NOT_DROPPED;
1591 return;
1592 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001593 token = mWindowTokenWithPointerCapture;
1594 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001595 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001596 setPointerCaptureLocked(false);
1597 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001598 }
1599
1600 auto channel = getInputChannelLocked(token);
1601 if (channel == nullptr) {
1602 // Window has gone away, clean up Pointer Capture state.
1603 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001604 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001605 setPointerCaptureLocked(false);
1606 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001607 return;
1608 }
1609 InputTarget target;
1610 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001611 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001612 entry->dispatchInProgress = true;
1613 dispatchEventLocked(currentTime, entry, {target});
1614
1615 dropReason = DropReason::NOT_DROPPED;
1616}
1617
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001618void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1619 const std::shared_ptr<TouchModeEntry>& entry) {
1620 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001621 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001622 if (windowHandles.empty()) {
1623 return;
1624 }
1625 const std::vector<InputTarget> inputTargets =
1626 getInputTargetsFromWindowHandlesLocked(windowHandles);
1627 if (inputTargets.empty()) {
1628 return;
1629 }
1630 entry->dispatchInProgress = true;
1631 dispatchEventLocked(currentTime, entry, inputTargets);
1632}
1633
1634std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1635 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1636 std::vector<InputTarget> inputTargets;
1637 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001638 const sp<IBinder>& token = handle->getToken();
1639 if (token == nullptr) {
1640 continue;
1641 }
1642 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1643 if (channel == nullptr) {
1644 continue; // Window has gone away
1645 }
1646 InputTarget target;
1647 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001648 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001649 inputTargets.push_back(target);
1650 }
1651 return inputTargets;
1652}
1653
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001654bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 if (!entry->dispatchInProgress) {
1658 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1659 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1660 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1661 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001662 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 // We have seen two identical key downs in a row which indicates that the device
1664 // driver is automatically generating key repeats itself. We take note of the
1665 // repeat here, but we disable our own next key repeat timer since it is clear that
1666 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001667 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1668 // Make sure we don't get key down from a different device. If a different
1669 // device Id has same key pressed down, the new device Id will replace the
1670 // current one to hold the key repeat with repeat count reset.
1671 // In the future when got a KEY_UP on the device id, drop it and do not
1672 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1674 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001675 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 } else {
1677 // Not a repeat. Save key down state in case we do see a repeat later.
1678 resetKeyRepeatLocked();
1679 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1680 }
1681 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001682 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1683 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001685 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001686 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1687 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001688 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 resetKeyRepeatLocked();
1690 }
1691
1692 if (entry->repeatCount == 1) {
1693 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1694 } else {
1695 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1696 }
1697
1698 entry->dispatchInProgress = true;
1699
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001700 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702
1703 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001704 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 if (currentTime < entry->interceptKeyWakeupTime) {
1706 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1707 *nextWakeupTime = entry->interceptKeyWakeupTime;
1708 }
1709 return false; // wait until next wakeup
1710 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001711 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 entry->interceptKeyWakeupTime = 0;
1713 }
1714
1715 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001716 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001718 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001719 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001720
1721 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1722 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1723 };
1724 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001725 // Poke user activity for keys not passed to user
1726 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 return false; // wait for the command to run
1728 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001729 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001731 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001732 if (*dropReason == DropReason::NOT_DROPPED) {
1733 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735 }
1736
1737 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001738 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1741 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001742 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001743 // Poke user activity for undispatched keys
1744 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 return true;
1746 }
1747
1748 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001749 InputEventInjectionResult injectionResult;
1750 sp<WindowInfoHandle> focusedWindow =
1751 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1752 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001753 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 return false;
1755 }
1756
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001757 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001758 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 return true;
1760 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001761 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1762
1763 std::vector<InputTarget> inputTargets;
1764 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001765 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001766 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001768 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001769 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770
1771 // Dispatch the key.
1772 dispatchEventLocked(currentTime, entry, inputTargets);
1773 return true;
1774}
1775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001776void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001777 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1778 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1779 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1780 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1781 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1782 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1783 entry.metaState, entry.repeatCount, entry.downTime);
1784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785}
1786
Prabir Pradhancef936d2021-07-21 16:17:52 +00001787void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1788 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001789 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001790 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1791 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1792 "source=0x%x, sensorType=%s",
1793 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001794 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001795 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001796 auto command = [this, entry]() REQUIRES(mLock) {
1797 scoped_unlock unlock(mLock);
1798
1799 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001800 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001801 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001802 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1803 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001804 };
1805 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001806}
1807
1808bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001809 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1810 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001811 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001812 }
Chris Yef59a2f42020-10-16 12:55:26 -07001813 { // acquire lock
1814 std::scoped_lock _l(mLock);
1815
1816 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1817 std::shared_ptr<EventEntry> entry = *it;
1818 if (entry->type == EventEntry::Type::SENSOR) {
1819 it = mInboundQueue.erase(it);
1820 releaseInboundEventLocked(entry);
1821 }
1822 }
1823 }
1824 return true;
1825}
1826
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001827bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001828 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001829 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001831 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 entry->dispatchInProgress = true;
1833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 }
1836
1837 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001838 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001839 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1841 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 return true;
1843 }
1844
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001845 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
1847 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001848 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849
1850 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 if (isPointerEvent) {
1853 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001854
1855 if (mDragState &&
1856 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1857 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1858 pilferPointersLocked(mDragState->dragWindow->getToken());
1859 }
1860
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001861 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001862 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001863 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001864 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1865 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 } else {
1867 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001868 sp<WindowInfoHandle> focusedWindow =
1869 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1870 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1871 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1872 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001873 InputTarget::Flags::FOREGROUND |
1874 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001875 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 return false;
1880 }
1881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001882 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001883 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001884 return true;
1885 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001887 CancelationOptions::Mode mode(
1888 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1889 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001890 CancelationOptions options(mode, "input event injection failed");
1891 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 return true;
1893 }
1894
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001895 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001896 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897
1898 // Dispatch the motion.
1899 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001900 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001901 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 synthesizeCancelationEventsForAllConnectionsLocked(options);
1903 }
1904 dispatchEventLocked(currentTime, entry, inputTargets);
1905 return true;
1906}
1907
chaviw98318de2021-05-19 16:45:23 -05001908void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001909 bool isExiting, const int32_t rawX,
1910 const int32_t rawY) {
1911 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001912 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001913 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1914 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001915
1916 enqueueInboundEventLocked(std::move(dragEntry));
1917}
1918
1919void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1920 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1921 if (channel == nullptr) {
1922 return; // Window has gone away
1923 }
1924 InputTarget target;
1925 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001926 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001927 entry->dispatchInProgress = true;
1928 dispatchEventLocked(currentTime, entry, {target});
1929}
1930
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001932 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001933 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001934 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001935 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001936 "metaState=0x%x, buttonState=0x%x,"
1937 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001938 prefix, entry.eventTime, entry.deviceId,
1939 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1940 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1941 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1942 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001944 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001945 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001946 "x=%f, y=%f, pressure=%f, size=%f, "
1947 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1948 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001949 i, entry.pointerProperties[i].id,
1950 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1952 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1953 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1954 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1955 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1956 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1957 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1958 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1959 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962}
1963
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001964void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1965 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001966 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001967 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001968 if (DEBUG_DISPATCH_CYCLE) {
1969 ALOGD("dispatchEventToCurrentInputTargets");
1970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001972 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001973
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1975
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001976 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001978 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001979 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001980 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001981 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001982 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001984 if (DEBUG_FOCUS) {
1985 ALOGD("Dropping event delivery to target with channel '%s' because it "
1986 "is no longer registered with the input dispatcher.",
1987 inputTarget.inputChannel->getName().c_str());
1988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
1990 }
1991}
1992
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001993void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1995 // If the policy decides to close the app, we will get a channel removal event via
1996 // unregisterInputChannel, and will clean up the connection that way. We are already not
1997 // sending new pointers to the connection when it blocked, but focused events will continue to
1998 // pile up.
1999 ALOGW("Canceling events for %s because it is unresponsive",
2000 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002001 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002002 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002003 "application not responding");
2004 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 }
2006}
2007
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002008void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002009 if (DEBUG_FOCUS) {
2010 ALOGD("Resetting ANR timeouts.");
2011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012
2013 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002015 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016}
2017
Tiger Huang721e26f2018-07-24 22:26:19 +08002018/**
2019 * Get the display id that the given event should go to. If this event specifies a valid display id,
2020 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2021 * Focused display is the display that the user most recently interacted with.
2022 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002024 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002025 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002026 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002027 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2028 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 break;
2030 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002031 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2033 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002034 break;
2035 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002036 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002037 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002038 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002039 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002040 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002041 case EventEntry::Type::SENSOR:
2042 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002043 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 return ADISPLAY_ID_NONE;
2045 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002046 }
2047 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2048}
2049
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2051 const char* focusedWindowName) {
2052 if (mAnrTracker.empty()) {
2053 // already processed all events that we waited for
2054 mKeyIsWaitingForEventsTimeout = std::nullopt;
2055 return false;
2056 }
2057
2058 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2059 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002060 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002061 mKeyIsWaitingForEventsTimeout = currentTime +
2062 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2063 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 return true;
2065 }
2066
2067 // We still have pending events, and already started the timer
2068 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2069 return true; // Still waiting
2070 }
2071
2072 // Waited too long, and some connection still hasn't processed all motions
2073 // Just send the key to the focused window
2074 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2075 focusedWindowName);
2076 mKeyIsWaitingForEventsTimeout = std::nullopt;
2077 return false;
2078}
2079
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002080sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2081 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2082 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002083 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002084 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
Tiger Huang721e26f2018-07-24 22:26:19 +08002086 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002087 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002088 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002089 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2090
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 // If there is no currently focused window and no focused application
2092 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002093 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2094 ALOGI("Dropping %s event because there is no focused window or focused application in "
2095 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002096 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002097 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
2099
Vishnu Nair062a8672021-09-03 16:07:44 -07002100 // Drop key events if requested by input feature
2101 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002102 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002103 }
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2106 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2107 // start interacting with another application via touch (app switch). This code can be removed
2108 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2109 // an app is expected to have a focused window.
2110 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2111 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2112 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002113 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2114 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2115 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002117 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 ALOGW("Waiting because no window has focus but %s may eventually add a "
2119 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002120 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002122 outInjectionResult = InputEventInjectionResult::PENDING;
2123 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002124 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2125 // Already raised ANR. Drop the event
2126 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002127 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002128 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002129 } else {
2130 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002131 outInjectionResult = InputEventInjectionResult::PENDING;
2132 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002133 }
2134 }
2135
2136 // we have a valid, non-null focused window
2137 resetNoFocusedWindowTimeoutLocked();
2138
Prabir Pradhan5735a322022-04-11 17:23:34 +00002139 // Verify targeted injection.
2140 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2141 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002142 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2143 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 }
2145
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002146 if (focusedWindowHandle->getInfo()->inputConfig.test(
2147 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002148 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002149 outInjectionResult = InputEventInjectionResult::PENDING;
2150 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 }
2152
2153 // If the event is a key event, then we must wait for all previous events to
2154 // complete before delivering it because previous events may have the
2155 // side-effect of transferring focus to a different window and we want to
2156 // ensure that the following keys are sent to the new window.
2157 //
2158 // Suppose the user touches a button in a window then immediately presses "A".
2159 // If the button causes a pop-up window to appear then we want to ensure that
2160 // the "A" key is delivered to the new pop-up window. This is because users
2161 // often anticipate pending UI changes when typing on a keyboard.
2162 // To obtain this behavior, we must serialize key events with respect to all
2163 // prior input events.
2164 if (entry.type == EventEntry::Type::KEY) {
2165 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2166 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002167 outInjectionResult = InputEventInjectionResult::PENDING;
2168 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002172 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2173 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174}
2175
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176/**
2177 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2178 * that are currently unresponsive.
2179 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002180std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2181 const std::vector<Monitor>& monitors) const {
2182 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002183 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002184 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002185 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002186 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002187 if (connection == nullptr) {
2188 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002189 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002190 return false;
2191 }
2192 if (!connection->responsive) {
2193 ALOGW("Unresponsive monitor %s will not get the new gesture",
2194 connection->inputChannel->getName().c_str());
2195 return false;
2196 }
2197 return true;
2198 });
2199 return responsiveMonitors;
2200}
2201
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002202/**
2203 * In general, touch should be always split between windows. Some exceptions:
2204 * 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 -07002205 * from the same device, *and* the window that's receiving the current pointer does not support
2206 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002207 * 2. Don't split mouse events
2208 */
2209bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2210 const MotionEntry& entry) const {
2211 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2212 // We should never split mouse events
2213 return false;
2214 }
2215 for (const TouchedWindow& touchedWindow : touchState.windows) {
2216 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2217 // Spy windows should not affect whether or not touch is split.
2218 continue;
2219 }
2220 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2221 continue;
2222 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002223 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2224 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2225 // Wallpaper window should not affect whether or not touch is split
2226 continue;
2227 }
2228
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002229 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002230 return false;
2231 }
2232 }
2233 return true;
2234}
2235
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002236std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002237 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2238 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002239 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002241 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // For security reasons, we defer updating the touch state until we are sure that
2243 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 const int32_t displayId = entry.displayId;
2245 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002246 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247
2248 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002249 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 // Copy current touch state into tempTouchState.
2252 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2253 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002254 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002256 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2257 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002258 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002259 }
2260
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002261 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002262 bool switchedDevice = false;
2263 if (oldState != nullptr) {
2264 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2265 const bool anotherDeviceIsActive =
2266 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2267 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002268 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002269
2270 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2272 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002273 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2274 // touchable windows.
2275 const bool wasDown = oldState != nullptr && oldState->isDown();
2276 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2277 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002278 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2279 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2280 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002281 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002282
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002283 // If pointers are already down, let's finish the current gesture and ignore the new events
2284 // from another device. However, if the new event is a down event, let's cancel the current
2285 // touch and let the new one take over.
2286 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002287 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002288 << " is already down in display " << displayId << ": " << entry.getDescription();
2289 // TODO(b/211379801): test multiple simultaneous input streams.
2290 outInjectionResult = InputEventInjectionResult::FAILED;
2291 return {}; // wrong device
2292 }
2293
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002295 // If a new gesture is starting, clear the touch state completely.
2296 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002298 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002299 ALOGI("Dropping move event because a pointer for a different device is already active "
2300 "in display %" PRId32,
2301 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002302 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002303 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002304 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002307 if (isHoverAction) {
2308 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2309 // all of the existing hovering pointers and recompute.
2310 tempTouchState.clearHoveringPointers();
2311 }
2312
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2314 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002315 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002316 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002317 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2318 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002319 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002320 auto [newTouchedWindowHandle, outsideTargets] =
2321 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002322
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002323 if (isDown) {
2324 targets += outsideTargets;
2325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002327 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002328 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002330 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 }
2332
Prabir Pradhan5735a322022-04-11 17:23:34 +00002333 // Verify targeted injection.
2334 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2335 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002336 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002337 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002338 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002339 }
2340
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002341 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002343 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2344 // New window supports splitting, but we should never split mouse events.
2345 isSplit = !isFromMouse;
2346 } else if (isSplit) {
2347 // New window does not support splitting but we have already split events.
2348 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 newTouchedWindowHandle = nullptr;
2350 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351 } else {
2352 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002353 // be delivered to a new window which supports split touch. Pointers from a mouse device
2354 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002355 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002356 }
2357
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002358 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002359 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002360 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002361 // Process the foreground window first so that it is the first to receive the event.
2362 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002363 }
2364
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002365 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002366 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2367 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002368 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002369 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002370 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002371 }
2372
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002374 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002375 continue;
2376 }
2377
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002378 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2379 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002380 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002381 // The "windowHandle" is the target of this hovering pointer.
2382 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002383 }
2384
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002386 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002388 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2389 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002391 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392
2393 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002394 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002395 }
2396 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002397 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002399 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002401
2402 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002403 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002404 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002405 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002406 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002407
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002408 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2409 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2410
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002411 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2412 // still add a window to the touch state. We should avoid doing that, but some of the
2413 // later checks ("at least one foreground window") rely on this in order to dispatch
2414 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002415 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002416 isDownOrPointerDown
2417 ? std::make_optional(entry.eventTime)
2418 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002419
2420 // If this is the pointer going down and the touched window has a wallpaper
2421 // then also add the touched wallpaper windows so they are locked in for the duration
2422 // of the touch gesture.
2423 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2424 // engine only supports touch events. We would need to add a mechanism similar
2425 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002426 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002427 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2428 windowHandle->getInfo()->inputConfig.test(
2429 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2430 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2431 if (wallpaper != nullptr) {
2432 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2433 InputTarget::Flags::WINDOW_IS_OBSCURED |
2434 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2435 InputTarget::Flags::DISPATCH_AS_IS;
2436 if (isSplit) {
2437 wallpaperFlags |= InputTarget::Flags::SPLIT;
2438 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002439 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2440 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002441 }
2442 }
2443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002445
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002446 // If a window is already pilfering some pointers, give it this new pointer as well and
2447 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2448 // which is a specific behaviour that we want.
2449 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2450 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002451 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2452 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002453 // This window is already pilfering some pointers, and this new pointer is also
2454 // going to it. Therefore, take over this pointer and don't give it to anyone
2455 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002456 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002457 }
2458 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002459
2460 // Restrict all pilfered pointers to the pilfering windows.
2461 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 } else {
2463 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2464
2465 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002466 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002467 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2468 "dropped the pointer down event in display "
2469 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002470 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002471 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 }
2473
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002474 // If the pointer is not currently hovering, then ignore the event.
2475 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2476 const int32_t pointerId = entry.pointerProperties[0].id;
2477 if (oldState == nullptr ||
2478 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2479 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2480 "display "
2481 << displayId << ": " << entry.getDescription();
2482 outInjectionResult = InputEventInjectionResult::FAILED;
2483 return {};
2484 }
2485 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2486 }
2487
arthurhung6d4bed92021-03-17 11:59:33 +08002488 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002489
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002491 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002492 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002493 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002494 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002495 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002496 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002497 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002498 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002499
Prabir Pradhan5735a322022-04-11 17:23:34 +00002500 // Verify targeted injection.
2501 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2502 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002503 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002504 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002505 }
2506
Vishnu Nair062a8672021-09-03 16:07:44 -07002507 // Drop touch events if requested by input feature
2508 if (newTouchedWindowHandle != nullptr &&
2509 shouldDropInput(entry, newTouchedWindowHandle)) {
2510 newTouchedWindowHandle = nullptr;
2511 }
2512
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002513 if (newTouchedWindowHandle != nullptr &&
2514 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002515 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2516 oldTouchedWindowHandle->getName().c_str(),
2517 newTouchedWindowHandle->getName().c_str(), displayId);
2518
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002520 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002521 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002522 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002523
2524 const TouchedWindow& touchedWindow =
2525 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2526 addWindowTargetLocked(oldTouchedWindowHandle,
2527 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002528 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529
2530 // Make a slippery entrance into the new window.
2531 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002532 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002535 ftl::Flags<InputTarget::Flags> targetFlags =
2536 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002537 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002538 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002541 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
2543 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002544 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002545 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002546 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002549 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2550 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002551
2552 // Check if the wallpaper window should deliver the corresponding event.
2553 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002554 tempTouchState, entry.deviceId, pointerId, targets);
2555 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2556 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558 }
Arthur Hung96483742022-11-15 03:30:48 +00002559
2560 // Update the pointerIds for non-splittable when it received pointer down.
2561 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2562 // If no split, we suppose all touched windows should receive pointer down.
2563 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2564 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2565 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2566 // Ignore drag window for it should just track one pointer.
2567 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2568 continue;
2569 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002570 touchedWindow.addTouchingPointer(entry.deviceId,
2571 entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002572 }
2573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 }
2575
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002576 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002577 {
2578 std::vector<TouchedWindow> hoveringWindows =
2579 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2580 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002581 std::optional<InputTarget> target =
2582 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002583 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002584 if (!target) {
2585 continue;
2586 }
2587 // Hardcode to single hovering pointer for now.
2588 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2589 pointerIds.set(entry.pointerProperties[0].id);
2590 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2591 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594
Prabir Pradhan5735a322022-04-11 17:23:34 +00002595 // Ensure that all touched windows are valid for injection.
2596 if (entry.injectionState != nullptr) {
2597 std::string errs;
2598 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002599 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2600 if (err) errs += "\n - " + *err;
2601 }
2602 if (!errs.empty()) {
2603 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002604 "%s:%s",
2605 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002606 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002607 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002608 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002609 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002610
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002611 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2612 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002614 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002615 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002616 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002617 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002618 for (InputTarget& target : targets) {
2619 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2620 sp<WindowInfoHandle> targetWindow =
2621 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2622 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2623 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 }
2626 }
2627 }
2628 }
2629
Harry Cuttsb166c002023-05-09 13:06:05 +00002630 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2631 // only want the system UI to handle these gestures.
2632 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2633 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2634 if (isTouchpadNavGesture) {
2635 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2636 }
2637
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002638 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002639 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002640 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2641 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002642 // Windows with hovering pointers are getting persisted inside TouchState.
2643 // Do not send this event to those windows.
2644 continue;
2645 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002646
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002647 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002648 touchedWindow.getTouchingPointers(entry.deviceId),
2649 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002650 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002651
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002652 // During targeted injection, only allow owned targets to receive events
2653 std::erase_if(targets, [&](const InputTarget& target) {
2654 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2655 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2656 if (err) {
2657 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2658 << ": " << (*err);
2659 return true;
2660 }
2661 return false;
2662 });
2663
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002664 if (targets.empty()) {
2665 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2666 outInjectionResult = InputEventInjectionResult::FAILED;
2667 return {};
2668 }
2669
2670 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2671 // window that is actually receiving the entire gesture.
2672 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2673 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2674 })) {
2675 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2676 << entry.getDescription();
2677 outInjectionResult = InputEventInjectionResult::FAILED;
2678 return {};
2679 }
2680
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002681 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002682 // Drop the outside or hover touch windows since we will not care about them
2683 // in the next iteration.
2684 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002687 if (switchedDevice) {
2688 if (DEBUG_FOCUS) {
2689 ALOGD("Conflicting pointer actions: Switched to a different device.");
2690 }
2691 *outConflictingPointerActions = true;
2692 }
2693
2694 if (isHoverAction) {
2695 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002696 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002697 ALOGD_IF(DEBUG_FOCUS,
2698 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002699 *outConflictingPointerActions = true;
2700 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002701 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2702 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002703 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002704 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2705 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002706 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002707 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002708 // All pointers up or canceled.
2709 tempTouchState.reset();
2710 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2711 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002712 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2713 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002715 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002716 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2717 // One pointer went up.
2718 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2719 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002721 for (size_t i = 0; i < tempTouchState.windows.size();) {
2722 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002723 touchedWindow.removeTouchingPointer(entry.deviceId, pointerId);
2724 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002725 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2726 continue;
2727 }
2728 i += 1;
2729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 }
2731
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002732 // Save changes unless the action was scroll in which case the temporary touch
2733 // state was only valid for this one action.
2734 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002735 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002736 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 mTouchStatesByDisplay[displayId] = tempTouchState;
2738 } else {
2739 mTouchStatesByDisplay.erase(displayId);
2740 }
2741 }
2742
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002743 if (tempTouchState.windows.empty()) {
2744 mTouchStatesByDisplay.erase(displayId);
2745 }
2746
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002747 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748}
2749
arthurhung6d4bed92021-03-17 11:59:33 +08002750void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002751 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2752 // have an explicit reason to support it.
2753 constexpr bool isStylus = false;
2754
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002755 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002756 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002757 if (dropWindow) {
2758 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002759 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002760 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002761 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002762 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002763 }
2764 mDragState.reset();
2765}
2766
2767void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002768 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002769 return;
2770 }
2771
arthurhung6d4bed92021-03-17 11:59:33 +08002772 if (!mDragState->isStartDrag) {
2773 mDragState->isStartDrag = true;
2774 mDragState->isStylusButtonDownAtStart =
2775 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2776 }
2777
Arthur Hung54745652022-04-20 07:17:41 +00002778 // Find the pointer index by id.
2779 int32_t pointerIndex = 0;
2780 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2781 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2782 if (pointerProperties.id == mDragState->pointerId) {
2783 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002784 }
Arthur Hung54745652022-04-20 07:17:41 +00002785 }
arthurhung6d4bed92021-03-17 11:59:33 +08002786
Arthur Hung54745652022-04-20 07:17:41 +00002787 if (uint32_t(pointerIndex) == entry.pointerCount) {
2788 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002789 }
2790
2791 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2792 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2793 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2794
2795 switch (maskedAction) {
2796 case AMOTION_EVENT_ACTION_MOVE: {
2797 // Handle the special case : stylus button no longer pressed.
2798 bool isStylusButtonDown =
2799 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2800 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2801 finishDragAndDrop(entry.displayId, x, y);
2802 return;
2803 }
2804
2805 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2806 // until we have an explicit reason to support it.
2807 constexpr bool isStylus = false;
2808
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002809 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002810 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002811 // enqueue drag exit if needed.
2812 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2813 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2814 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002815 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002816 y);
2817 }
2818 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2819 }
2820 // enqueue drag location if needed.
2821 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002822 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002823 }
2824 break;
2825 }
2826
2827 case AMOTION_EVENT_ACTION_POINTER_UP:
2828 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2829 break;
2830 }
2831 // The drag pointer is up.
2832 [[fallthrough]];
2833 case AMOTION_EVENT_ACTION_UP:
2834 finishDragAndDrop(entry.displayId, x, y);
2835 break;
2836 case AMOTION_EVENT_ACTION_CANCEL: {
2837 ALOGD("Receiving cancel when drag and drop.");
2838 sendDropWindowCommandLocked(nullptr, 0, 0);
2839 mDragState.reset();
2840 break;
2841 }
arthurhungb89ccb02020-12-30 16:19:01 +08002842 }
2843}
2844
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002845std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2846 const sp<android::gui::WindowInfoHandle>& windowHandle,
2847 ftl::Flags<InputTarget::Flags> targetFlags,
2848 std::optional<nsecs_t> firstDownTimeInTarget) const {
2849 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2850 if (inputChannel == nullptr) {
2851 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2852 return {};
2853 }
2854 InputTarget inputTarget;
2855 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002856 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002857 inputTarget.flags = targetFlags;
2858 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2859 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2860 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2861 if (displayInfoIt != mDisplayInfos.end()) {
2862 inputTarget.displayTransform = displayInfoIt->second.transform;
2863 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002864 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002865 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2866 }
2867 return inputTarget;
2868}
2869
chaviw98318de2021-05-19 16:45:23 -05002870void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002871 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002872 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002873 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002874 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002875 std::vector<InputTarget>::iterator it =
2876 std::find_if(inputTargets.begin(), inputTargets.end(),
2877 [&windowHandle](const InputTarget& inputTarget) {
2878 return inputTarget.inputChannel->getConnectionToken() ==
2879 windowHandle->getToken();
2880 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002881
chaviw98318de2021-05-19 16:45:23 -05002882 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883
2884 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002885 std::optional<InputTarget> target =
2886 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2887 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002888 return;
2889 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002890 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002891 it = inputTargets.end() - 1;
2892 }
2893
2894 ALOG_ASSERT(it->flags == targetFlags);
2895 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2896
chaviw1ff3d1e2020-07-01 15:53:47 -07002897 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898}
2899
Michael Wright3dd60e22019-03-27 22:06:44 +00002900void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002901 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002902 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2903 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002904
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002905 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2906 InputTarget target;
2907 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002908 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002909 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2910 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002911 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2912 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002913 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002914 target.setDefaultPointerTransform(target.displayTransform);
2915 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 }
2917}
2918
Robert Carrc9bf1d32020-04-13 17:21:08 -07002919/**
2920 * Indicate whether one window handle should be considered as obscuring
2921 * another window handle. We only check a few preconditions. Actually
2922 * checking the bounds is left to the caller.
2923 */
chaviw98318de2021-05-19 16:45:23 -05002924static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2925 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002926 // Compare by token so cloned layers aren't counted
2927 if (haveSameToken(windowHandle, otherHandle)) {
2928 return false;
2929 }
2930 auto info = windowHandle->getInfo();
2931 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002932 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002933 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002934 } else if (otherInfo->alpha == 0 &&
2935 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002936 // Those act as if they were invisible, so we don't need to flag them.
2937 // We do want to potentially flag touchable windows even if they have 0
2938 // opacity, since they can consume touches and alter the effects of the
2939 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002940 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002941 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2942 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002943 } else if (info->ownerUid == otherInfo->ownerUid) {
2944 // If ownerUid is the same we don't generate occlusion events as there
2945 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002946 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002948 return false;
2949 } else if (otherInfo->displayId != info->displayId) {
2950 return false;
2951 }
2952 return true;
2953}
2954
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002955/**
2956 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2957 * untrusted, one should check:
2958 *
2959 * 1. If result.hasBlockingOcclusion is true.
2960 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2961 * BLOCK_UNTRUSTED.
2962 *
2963 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2964 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2965 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2966 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2967 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2968 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2969 *
2970 * If neither of those is true, then it means the touch can be allowed.
2971 */
2972InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002973 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2974 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002975 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002976 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002977 TouchOcclusionInfo info;
2978 info.hasBlockingOcclusion = false;
2979 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002980 info.obscuringUid = gui::Uid::INVALID;
2981 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002982 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002983 if (windowHandle == otherHandle) {
2984 break; // All future windows are below us. Exit early.
2985 }
chaviw98318de2021-05-19 16:45:23 -05002986 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002987 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2988 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002989 if (DEBUG_TOUCH_OCCLUSION) {
2990 info.debugInfo.push_back(
2991 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2992 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002993 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2994 // we perform the checks below to see if the touch can be propagated or not based on the
2995 // window's touch occlusion mode
2996 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2997 info.hasBlockingOcclusion = true;
2998 info.obscuringUid = otherInfo->ownerUid;
2999 info.obscuringPackage = otherInfo->packageName;
3000 break;
3001 }
3002 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003003 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003004 float opacity =
3005 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3006 // Given windows A and B:
3007 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3008 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3009 opacityByUid[uid] = opacity;
3010 if (opacity > info.obscuringOpacity) {
3011 info.obscuringOpacity = opacity;
3012 info.obscuringUid = uid;
3013 info.obscuringPackage = otherInfo->packageName;
3014 }
3015 }
3016 }
3017 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003018 if (DEBUG_TOUCH_OCCLUSION) {
3019 info.debugInfo.push_back(
3020 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3021 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003022 return info;
3023}
3024
chaviw98318de2021-05-19 16:45:23 -05003025std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003026 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003027 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003028 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3029 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3030 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003031 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003032 info->ownerUid.toString().c_str(), info->id,
3033 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3034 info->frameTop, info->frameRight, info->frameBottom,
3035 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3036 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3037 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003038 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003039}
3040
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003041bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3042 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003043 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3044 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003045 return false;
3046 }
3047 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003048 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003049 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003050 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003051 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3052 return false;
3053 }
3054 return true;
3055}
3056
chaviw98318de2021-05-19 16:45:23 -05003057bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003060 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3061 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003062 if (windowHandle == otherHandle) {
3063 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
chaviw98318de2021-05-19 16:45:23 -05003065 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003066 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003067 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 return true;
3069 }
3070 }
3071 return false;
3072}
3073
chaviw98318de2021-05-19 16:45:23 -05003074bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003075 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003076 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3077 const WindowInfo* windowInfo = windowHandle->getInfo();
3078 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003079 if (windowHandle == otherHandle) {
3080 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003081 }
chaviw98318de2021-05-19 16:45:23 -05003082 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003083 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003084 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003085 return true;
3086 }
3087 }
3088 return false;
3089}
3090
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003091std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003092 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003093 if (applicationHandle != nullptr) {
3094 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003095 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 } else {
3097 return applicationHandle->getName();
3098 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003099 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003100 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003102 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
3104}
3105
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003106void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003107 if (!isUserActivityEvent(eventEntry)) {
3108 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003109 return;
3110 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003111 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003112 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003113 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003114 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003115 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003116 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003117 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
3119 }
3120
3121 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003123 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003124 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3125 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 return;
3127 }
Josep del Riob3981622023-04-18 15:49:45 +00003128 if (windowDisablingUserActivityInfo != nullptr) {
3129 if (DEBUG_DISPATCH_CYCLE) {
3130 ALOGD("Not poking user activity: disabled by window '%s'.",
3131 windowDisablingUserActivityInfo->name.c_str());
3132 }
3133 return;
3134 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003135 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 eventType = USER_ACTIVITY_EVENT_TOUCH;
3137 }
3138 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003140 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003141 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3142 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 return;
3144 }
Josep del Riob3981622023-04-18 15:49:45 +00003145 // If the key code is unknown, we don't consider it user activity
3146 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3147 return;
3148 }
3149 // Don't inhibit events that were intercepted or are not passed to
3150 // the apps, like system shortcuts
3151 if (windowDisablingUserActivityInfo != nullptr &&
3152 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3153 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3154 if (DEBUG_DISPATCH_CYCLE) {
3155 ALOGD("Not poking user activity: disabled by window '%s'.",
3156 windowDisablingUserActivityInfo->name.c_str());
3157 }
3158 return;
3159 }
3160
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 eventType = USER_ACTIVITY_EVENT_BUTTON;
3162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003164 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003165 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003166 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003167 break;
3168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 }
3170
Prabir Pradhancef936d2021-07-21 16:17:52 +00003171 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3172 REQUIRES(mLock) {
3173 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003174 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003175 };
3176 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177}
3178
3179void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003180 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003182 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003183 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003185 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003186 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003187 ATRACE_NAME(message.c_str());
3188 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003189 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003191 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003193 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003194 inputTarget.getPointerInfoString().c_str());
3195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196
3197 // Skip this event if the connection status is not normal.
3198 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003199 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 if (DEBUG_DISPATCH_CYCLE) {
3201 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003202 connection->getInputChannelName().c_str(),
3203 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 return;
3206 }
3207
3208 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003209 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003210 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003211 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003212 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003215 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003216 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3217 logDispatchStateLocked();
3218 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3219 "target on connection "
3220 << connection->getInputChannelName() << " for "
3221 << originalMotionEntry.getDescription();
3222 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003224 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3225 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 if (!splitMotionEntry) {
3227 return; // split event was dropped
3228 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003229 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3230 std::string reason = std::string("reason=pointer cancel on split window");
3231 android_log_event_list(LOGTAG_INPUT_CANCEL)
3232 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3233 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003234 if (DEBUG_FOCUS) {
3235 ALOGD("channel '%s' ~ Split motion event.",
3236 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003237 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003238 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3240 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 return;
3242 }
3243 }
3244
3245 // Not splitting. Enqueue dispatch entries for the event as is.
3246 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3247}
3248
3249void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003250 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003251 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003252 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003253 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003255 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003256 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003257 ATRACE_NAME(message.c_str());
3258 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003259 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3260 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003261
hongzuo liu95785e22022-09-06 02:51:35 +00003262 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263
3264 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003265 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003267 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003269 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003270 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
3278 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003279 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 startDispatchCycleLocked(currentTime, connection);
3281 }
3282}
3283
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003284void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003286 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003287 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003288 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3290 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003291 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003292 ATRACE_NAME(message.c_str());
3293 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3295 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 return;
3297 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298
3299 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3300 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 // This is a new event.
3303 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003304 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003305 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3308 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003314 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003315 dispatchEntry->resolvedAction = keyEntry.action;
3316 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3319 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003320 LOG(WARNING) << "channel " << connection->getInputChannelName()
3321 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 return; // skip the inconsistent event
3323 }
3324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003327 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003328 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003329 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3330 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3331 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3332 static_cast<int32_t>(IdGenerator::Source::OTHER);
3333 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003342 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3344 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003345 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003346 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 }
3348 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003349 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3350 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003351 if (DEBUG_DISPATCH_CYCLE) {
3352 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3353 "enter event",
3354 connection->getInputChannelName().c_str());
3355 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003356 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3357 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003361 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003362 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3364 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003365 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3367 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003368 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3373 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003374 LOG(WARNING) << "channel " << connection->getInputChannelName()
3375 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 return; // skip the inconsistent event
3377 }
3378
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003379 dispatchEntry->resolvedEventId =
3380 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3381 ? mIdGenerator.nextId()
3382 : motionEntry.id;
3383 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3384 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3385 ") to MotionEvent(id=0x%" PRIx32 ").",
3386 motionEntry.id, dispatchEntry->resolvedEventId);
3387 ATRACE_NAME(message.c_str());
3388 }
3389
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003390 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3391 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3392 // Skip reporting pointer down outside focus to the policy.
3393 break;
3394 }
3395
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003396 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003397 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398
3399 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003401 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003402 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003403 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3404 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003405 break;
3406 }
Chris Yef59a2f42020-10-16 12:55:26 -07003407 case EventEntry::Type::SENSOR: {
3408 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3409 break;
3410 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 case EventEntry::Type::CONFIGURATION_CHANGED:
3412 case EventEntry::Type::DEVICE_RESET: {
3413 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003414 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003415 break;
3416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 }
3418
3419 // Remember that we are waiting for this dispatch to complete.
3420 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003421 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
3423
3424 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003425 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003426 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003427}
3428
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003429/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003430 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003431 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003432 * The first role is to log input interaction with windows, which helps determine what the user was
3433 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3434 * that user started interacting with launcher window, as well as any other window that received
3435 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3436 * when the set of tokens that received the event changes. It is not logged again as long as the
3437 * user is interacting with the same windows.
3438 *
3439 * The second role is to track input device activity for metrics collection. For each input event,
3440 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3441 * input_interaction logs, the device interaction is reported even when the set of interaction
3442 * tokens do not change.
3443 *
3444 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3445 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003446 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003447void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3448 const std::vector<InputTarget>& targets) {
3449 int32_t deviceId;
3450 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003451 // Skip ACTION_UP events, and all events other than keys and motions
3452 if (entry.type == EventEntry::Type::KEY) {
3453 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3454 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3455 return;
3456 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003457 deviceId = keyEntry.deviceId;
3458 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 } else if (entry.type == EventEntry::Type::MOTION) {
3460 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3461 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003462 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3463 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003464 return;
3465 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003466 deviceId = motionEntry.deviceId;
3467 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003468 } else {
3469 return; // Not a key or a motion
3470 }
3471
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003472 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003473 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003474 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003476 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003477 continue; // Skip windows that receive ACTION_OUTSIDE
3478 }
3479
3480 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003481 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003482 if (connection == nullptr) {
3483 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003484 }
3485 newConnectionTokens.insert(std::move(token));
3486 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003487 if (target.windowHandle) {
3488 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3489 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003491
3492 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3493 REQUIRES(mLock) {
3494 scoped_unlock unlock(mLock);
3495 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3496 };
3497 postCommandLocked(std::move(command));
3498
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003499 if (newConnectionTokens == mInteractionConnectionTokens) {
3500 return; // no change
3501 }
3502 mInteractionConnectionTokens = newConnectionTokens;
3503
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003504 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003505 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003506 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003507 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003508 std::string message = "Interaction with: " + targetList;
3509 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003510 message += "<none>";
3511 }
3512 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3513}
3514
chaviwfd6d3512019-03-25 13:23:49 -07003515void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003516 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003517 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003518 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3519 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003520 return;
3521 }
3522
Vishnu Nairc519ff72021-01-21 08:23:08 -08003523 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003524 if (focusedToken == token) {
3525 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003526 return;
3527 }
3528
Prabir Pradhancef936d2021-07-21 16:17:52 +00003529 auto command = [this, token]() REQUIRES(mLock) {
3530 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003531 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003532 };
3533 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534}
3535
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003536status_t InputDispatcher::publishMotionEvent(Connection& connection,
3537 DispatchEntry& dispatchEntry) const {
3538 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3539 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3540
3541 PointerCoords scaledCoords[MAX_POINTERS];
3542 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3543
3544 // Set the X and Y offset and X and Y scale depending on the input source.
3545 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003546 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003547 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3548 if (globalScaleFactor != 1.0f) {
3549 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3550 scaledCoords[i] = motionEntry.pointerCoords[i];
3551 // Don't apply window scale here since we don't want scale to affect raw
3552 // coordinates. The scale will be sent back to the client and applied
3553 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003554 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003555 }
3556 usingCoords = scaledCoords;
3557 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003558 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003559 // We don't want the dispatch target to know the coordinates
3560 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3561 scaledCoords[i].clear();
3562 }
3563 usingCoords = scaledCoords;
3564 }
3565
3566 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3567
3568 // Publish the motion event.
3569 return connection.inputPublisher
3570 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3571 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3572 std::move(hmac), dispatchEntry.resolvedAction,
3573 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3574 motionEntry.edgeFlags, motionEntry.metaState,
3575 motionEntry.buttonState, motionEntry.classification,
3576 dispatchEntry.transform, motionEntry.xPrecision,
3577 motionEntry.yPrecision, motionEntry.xCursorPosition,
3578 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3579 motionEntry.downTime, motionEntry.eventTime,
3580 motionEntry.pointerCount, motionEntry.pointerProperties,
3581 usingCoords);
3582}
3583
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003585 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003586 if (ATRACE_ENABLED()) {
3587 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003589 ATRACE_NAME(message.c_str());
3590 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003591 if (DEBUG_DISPATCH_CYCLE) {
3592 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003595 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003596 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003598 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003599 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600
3601 // Publish the event.
3602 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003603 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3604 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003605 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003606 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3607 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003608 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3609 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3610 << connection->getInputChannelName();
3611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003614 status = connection->inputPublisher
3615 .publishKeyEvent(dispatchEntry->seq,
3616 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3617 keyEntry.source, keyEntry.displayId,
3618 std::move(hmac), dispatchEntry->resolvedAction,
3619 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3620 keyEntry.scanCode, keyEntry.metaState,
3621 keyEntry.repeatCount, keyEntry.downTime,
3622 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 }
3625
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003626 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003627 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3628 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3629 << connection->getInputChannelName();
3630 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003631 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003632 break;
3633 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003634
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003635 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003636 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003637 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003638 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003639 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003640 break;
3641 }
3642
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003643 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3644 const TouchModeEntry& touchModeEntry =
3645 static_cast<const TouchModeEntry&>(eventEntry);
3646 status = connection->inputPublisher
3647 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3648 touchModeEntry.inTouchMode);
3649
3650 break;
3651 }
3652
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3654 const auto& captureEntry =
3655 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3656 status = connection->inputPublisher
3657 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003658 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003659 break;
3660 }
3661
arthurhungb89ccb02020-12-30 16:19:01 +08003662 case EventEntry::Type::DRAG: {
3663 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3664 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3665 dragEntry.id, dragEntry.x,
3666 dragEntry.y,
3667 dragEntry.isExiting);
3668 break;
3669 }
3670
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003671 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003672 case EventEntry::Type::DEVICE_RESET:
3673 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003674 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003675 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
3679
3680 // Check the result.
3681 if (status) {
3682 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003683 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003685 "This is unexpected because the wait queue is empty, so the pipe "
3686 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003687 "event to it, status=%s(%d)",
3688 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3689 status);
Harry Cutts33476232023-01-30 19:57:29 +00003690 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 } else {
3692 // Pipe is full and we are waiting for the app to finish process some events
3693 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003694 if (DEBUG_DISPATCH_CYCLE) {
3695 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3696 "waiting for the application to catch up",
3697 connection->getInputChannelName().c_str());
3698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 }
3700 } else {
3701 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003702 "status=%s(%d)",
3703 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3704 status);
Harry Cutts33476232023-01-30 19:57:29 +00003705 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
3707 return;
3708 }
3709
3710 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003711 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3712 connection->outboundQueue.end(),
3713 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003714 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003715 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003716 if (connection->responsive) {
3717 mAnrTracker.insert(dispatchEntry->timeoutTime,
3718 connection->inputChannel->getConnectionToken());
3719 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003720 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 }
3722}
3723
chaviw09c8d2d2020-08-24 15:48:26 -07003724std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3725 size_t size;
3726 switch (event.type) {
3727 case VerifiedInputEvent::Type::KEY: {
3728 size = sizeof(VerifiedKeyEvent);
3729 break;
3730 }
3731 case VerifiedInputEvent::Type::MOTION: {
3732 size = sizeof(VerifiedMotionEvent);
3733 break;
3734 }
3735 }
3736 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3737 return mHmacKeyManager.sign(start, size);
3738}
3739
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003740const std::array<uint8_t, 32> InputDispatcher::getSignature(
3741 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003742 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003743 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744 // Only sign events up and down events as the purely move events
3745 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003746 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003747 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003748
3749 VerifiedMotionEvent verifiedEvent =
3750 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3751 verifiedEvent.actionMasked = actionMasked;
3752 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3753 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003754}
3755
3756const std::array<uint8_t, 32> InputDispatcher::getSignature(
3757 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3758 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3759 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3760 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003761 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003762}
3763
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003765 const std::shared_ptr<Connection>& connection,
3766 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003767 if (DEBUG_DISPATCH_CYCLE) {
3768 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3769 connection->getInputChannelName().c_str(), seq, toString(handled));
3770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003772 if (connection->status == Connection::Status::BROKEN ||
3773 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 return;
3775 }
3776
3777 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003778 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3779 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3780 };
3781 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782}
3783
3784void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003785 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003787 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003788 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3789 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791
3792 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003793 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003794 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003795 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003796 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797
3798 // The connection appears to be unrecoverably broken.
3799 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003800 if (connection->status == Connection::Status::NORMAL) {
3801 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802
3803 if (notify) {
3804 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003805 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3806 connection->getInputChannelName().c_str());
3807
3808 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003809 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003810 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003811 };
3812 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814 }
3815}
3816
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003817void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3818 while (!queue.empty()) {
3819 DispatchEntry* dispatchEntry = queue.front();
3820 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003821 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
3823}
3824
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003825void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003827 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829 delete dispatchEntry;
3830}
3831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003832int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3833 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003834 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003835 if (connection == nullptr) {
3836 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3837 connectionToken.get(), events);
3838 return 0; // remove the callback
3839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003841 bool notify;
3842 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3843 if (!(events & ALOOPER_EVENT_INPUT)) {
3844 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3845 "events=0x%x",
3846 connection->getInputChannelName().c_str(), events);
3847 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003850 nsecs_t currentTime = now();
3851 bool gotOne = false;
3852 status_t status = OK;
3853 for (;;) {
3854 Result<InputPublisher::ConsumerResponse> result =
3855 connection->inputPublisher.receiveConsumerResponse();
3856 if (!result.ok()) {
3857 status = result.error().code();
3858 break;
3859 }
3860
3861 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3862 const InputPublisher::Finished& finish =
3863 std::get<InputPublisher::Finished>(*result);
3864 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3865 finish.consumeTime);
3866 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003867 if (shouldReportMetricsForConnection(*connection)) {
3868 const InputPublisher::Timeline& timeline =
3869 std::get<InputPublisher::Timeline>(*result);
3870 mLatencyTracker
3871 .trackGraphicsLatency(timeline.inputEventId,
3872 connection->inputChannel->getConnectionToken(),
3873 std::move(timeline.graphicsTimeline));
3874 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 }
3876 gotOne = true;
3877 }
3878 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003879 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003880 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 return 1;
3882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 }
3884
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003885 notify = status != DEAD_OBJECT || !connection->monitor;
3886 if (notify) {
3887 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3888 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3889 status);
3890 }
3891 } else {
3892 // Monitor channels are never explicitly unregistered.
3893 // We do it automatically when the remote endpoint is closed so don't warn about them.
3894 const bool stillHaveWindowHandle =
3895 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3896 notify = !connection->monitor && stillHaveWindowHandle;
3897 if (notify) {
3898 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3899 connection->getInputChannelName().c_str(), events);
3900 }
3901 }
3902
3903 // Remove the channel.
3904 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3905 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906}
3907
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003910 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003911 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 }
3913}
3914
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003915void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003916 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003917 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003918 for (const Monitor& monitor : monitors) {
3919 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003920 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003921 }
3922}
3923
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003925 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003926 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003927 if (connection == nullptr) {
3928 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003930
3931 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932}
3933
3934void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003935 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Lia4659fc2023-07-14 14:36:22 +08003936 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3937 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3938 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3939 LOG(INFO) << __func__
3940 << ": Canceling drag and drop because the pointers for the drag window are being "
3941 "canceled.";
3942 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3943 mDragState.reset();
3944 }
3945
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003946 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 return;
3948 }
3949
3950 nsecs_t currentTime = now();
3951
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003952 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003953 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003955 if (cancelationEvents.empty()) {
3956 return;
3957 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003958 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3959 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003960 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003961 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003962 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003963 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003964
Arthur Hungb3307ee2021-10-14 10:57:37 +00003965 std::string reason = std::string("reason=").append(options.reason);
3966 android_log_event_list(LOGTAG_INPUT_CANCEL)
3967 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3968
Svet Ganov5d3bc372020-01-26 23:11:07 -08003969 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003970 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003971 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3972 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003973 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003974 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003975 target.globalScaleFactor = windowInfo->globalScaleFactor;
3976 }
3977 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003978 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003979
hongzuo liu95785e22022-09-06 02:51:35 +00003980 const bool wasEmpty = connection->outboundQueue.empty();
3981
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003982 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003983 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003984 switch (cancelationEventEntry->type) {
3985 case EventEntry::Type::KEY: {
3986 logOutboundKeyDetails("cancel - ",
3987 static_cast<const KeyEntry&>(*cancelationEventEntry));
3988 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003990 case EventEntry::Type::MOTION: {
3991 logOutboundMotionDetails("cancel - ",
3992 static_cast<const MotionEntry&>(*cancelationEventEntry));
3993 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003995 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003996 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003997 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3998 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003999 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004000 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004001 break;
4002 }
4003 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004004 case EventEntry::Type::DEVICE_RESET:
4005 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004006 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004007 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004008 break;
4009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 }
4011
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004012 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004013 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004015
hongzuo liu95785e22022-09-06 02:51:35 +00004016 // If the outbound queue was previously empty, start the dispatch cycle going.
4017 if (wasEmpty && !connection->outboundQueue.empty()) {
4018 startDispatchCycleLocked(currentTime, connection);
4019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020}
4021
Svet Ganov5d3bc372020-01-26 23:11:07 -08004022void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004023 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004024 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004025 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026 return;
4027 }
4028
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004029 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004030 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004031
4032 if (downEvents.empty()) {
4033 return;
4034 }
4035
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004036 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004037 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4038 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004040
4041 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004042 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004043 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4044 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004045 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004046 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004047 target.globalScaleFactor = windowInfo->globalScaleFactor;
4048 }
4049 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004050 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004051
hongzuo liu95785e22022-09-06 02:51:35 +00004052 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004053 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054 switch (downEventEntry->type) {
4055 case EventEntry::Type::MOTION: {
4056 logOutboundMotionDetails("down - ",
4057 static_cast<const MotionEntry&>(*downEventEntry));
4058 break;
4059 }
4060
4061 case EventEntry::Type::KEY:
4062 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004063 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004064 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004065 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004066 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004067 case EventEntry::Type::SENSOR:
4068 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004069 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004070 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004071 break;
4072 }
4073 }
4074
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004075 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004076 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004077 }
4078
hongzuo liu95785e22022-09-06 02:51:35 +00004079 // If the outbound queue was previously empty, start the dispatch cycle going.
4080 if (wasEmpty && !connection->outboundQueue.empty()) {
4081 startDispatchCycleLocked(downTime, connection);
4082 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004083}
4084
Arthur Hungc539dbb2022-12-08 07:45:36 +00004085void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4086 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4087 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004088 std::shared_ptr<Connection> wallpaperConnection =
4089 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004090 if (wallpaperConnection != nullptr) {
4091 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4092 }
4093 }
4094}
4095
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004097 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4098 nsecs_t splitDownTime) {
4099 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100
4101 uint32_t splitPointerIndexMap[MAX_POINTERS];
4102 PointerProperties splitPointerProperties[MAX_POINTERS];
4103 PointerCoords splitPointerCoords[MAX_POINTERS];
4104
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004105 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 uint32_t splitPointerCount = 0;
4107
4108 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004111 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004113 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4115 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4116 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004117 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 splitPointerCount += 1;
4119 }
4120 }
4121
4122 if (splitPointerCount != pointerIds.count()) {
4123 // This is bad. We are missing some of the pointers that we expected to deliver.
4124 // Most likely this indicates that we received an ACTION_MOVE events that has
4125 // different pointer ids than we expected based on the previous ACTION_DOWN
4126 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4127 // in this way.
4128 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004129 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004130 "a broken sequence of pointer ids from the input device: %s",
4131 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004132 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
4134
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004135 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4138 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4140 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004141 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004143 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 if (pointerIds.count() == 1) {
4145 // The first/last pointer went down/up.
4146 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004147 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004148 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4149 ? AMOTION_EVENT_ACTION_CANCEL
4150 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 } else {
4152 // A secondary pointer went down/up.
4153 uint32_t splitPointerIndex = 0;
4154 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4155 splitPointerIndex += 1;
4156 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 action = maskedAction |
4158 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 }
4160 } else {
4161 // An unrelated pointer changed.
4162 action = AMOTION_EVENT_ACTION_MOVE;
4163 }
4164 }
4165
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004166 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4167 logDispatchStateLocked();
4168 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4169 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4170 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004171 }
4172
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004173 int32_t newId = mIdGenerator.nextId();
4174 if (ATRACE_ENABLED()) {
4175 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4176 ") to MotionEvent(id=0x%" PRIx32 ").",
4177 originalMotionEntry.id, newId);
4178 ATRACE_NAME(message.c_str());
4179 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004180 std::unique_ptr<MotionEntry> splitMotionEntry =
4181 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4182 originalMotionEntry.deviceId, originalMotionEntry.source,
4183 originalMotionEntry.displayId,
4184 originalMotionEntry.policyFlags, action,
4185 originalMotionEntry.actionButton,
4186 originalMotionEntry.flags, originalMotionEntry.metaState,
4187 originalMotionEntry.buttonState,
4188 originalMotionEntry.classification,
4189 originalMotionEntry.edgeFlags,
4190 originalMotionEntry.xPrecision,
4191 originalMotionEntry.yPrecision,
4192 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004193 originalMotionEntry.yCursorPosition, splitDownTime,
4194 splitPointerCount, splitPointerProperties,
4195 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004197 if (originalMotionEntry.injectionState) {
4198 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 splitMotionEntry->injectionState->refCount += 1;
4200 }
4201
4202 return splitMotionEntry;
4203}
4204
Prabir Pradhan678438e2023-04-13 19:32:51 +00004205void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004206 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004207 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209
Antonio Kantekf16f2832021-09-28 04:39:20 +00004210 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004212 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004214 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004215 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004216 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 } // release lock
4218
4219 if (needWake) {
4220 mLooper->wake();
4221 }
4222}
4223
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004224/**
4225 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004226 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4227 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4228 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4229 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4230 * potentially handle the back key presses.
4231 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4232 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004233 */
4234void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004236 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4237 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004238 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004239 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004240 }
4241 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004242 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004243 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004244 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004245 keyCode = newKeyCode;
4246 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4247 }
4248 } else if (action == AKEY_EVENT_ACTION_UP) {
4249 // In order to maintain a consistent stream of up and down events, check to see if the key
4250 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4251 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004252 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004253 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004254 auto replacementIt = mReplacedKeys.find(replacement);
4255 if (replacementIt != mReplacedKeys.end()) {
4256 keyCode = replacementIt->second;
4257 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004258 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4259 }
4260 }
4261}
4262
Prabir Pradhan678438e2023-04-13 19:32:51 +00004263void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004264 ALOGD_IF(debugInboundEventDetails(),
4265 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4266 ", deviceId=%d, source=%s, displayId=%" PRId32
4267 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4268 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004269 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4270 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4271 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004272 Result<void> keyCheck = validateKeyEvent(args.action);
4273 if (!keyCheck.ok()) {
4274 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 return;
4276 }
4277
Prabir Pradhan678438e2023-04-13 19:32:51 +00004278 uint32_t policyFlags = args.policyFlags;
4279 int32_t flags = args.flags;
4280 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004281 // InputDispatcher tracks and generates key repeats on behalf of
4282 // whatever notifies it, so repeatCount should always be set to 0
4283 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4285 policyFlags |= POLICY_FLAG_VIRTUAL;
4286 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 if (policyFlags & POLICY_FLAG_FUNCTION) {
4289 metaState |= AMETA_FUNCTION_ON;
4290 }
4291
4292 policyFlags |= POLICY_FLAG_TRUSTED;
4293
Prabir Pradhan678438e2023-04-13 19:32:51 +00004294 int32_t keyCode = args.keyCode;
4295 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004296
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004298 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4299 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4300 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301
Michael Wright2b3c3302018-03-02 17:19:13 +00004302 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004303 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004304 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4305 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
Antonio Kantekf16f2832021-09-28 04:39:20 +00004309 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 { // acquire lock
4311 mLock.lock();
4312
4313 if (shouldSendKeyToInputFilterLocked(args)) {
4314 mLock.unlock();
4315
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004316 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004317 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 return; // event was consumed by the filter
4319 }
4320
4321 mLock.lock();
4322 }
4323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004324 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004325 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4326 args.displayId, policyFlags, args.action, flags, keyCode,
4327 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004329 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 mLock.unlock();
4331 } // release lock
4332
4333 if (needWake) {
4334 mLooper->wake();
4335 }
4336}
4337
Prabir Pradhan678438e2023-04-13 19:32:51 +00004338bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 return mInputFilterEnabled;
4340}
4341
Prabir Pradhan678438e2023-04-13 19:32:51 +00004342void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004343 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004344 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004345 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004346 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004347 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4348 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004349 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4350 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4351 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4352 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4353 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004354 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004355 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4356 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004357 i, args.pointerProperties[i].id,
4358 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4359 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4360 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4361 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4362 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4363 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4364 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4365 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4366 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4367 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004370
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004371 Result<void> motionCheck =
4372 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4373 args.pointerProperties.data());
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004374 if (!motionCheck.ok()) {
4375 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004376 return;
4377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004379 if (DEBUG_VERIFY_EVENTS) {
4380 auto [it, _] =
4381 mVerifiersByDisplay.try_emplace(args.displayId,
4382 StringPrintf("display %" PRId32, args.displayId));
4383 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004384 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4385 args.pointerProperties.data(), args.pointerCoords.data(),
4386 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004387 if (!result.ok()) {
4388 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4389 }
4390 }
4391
Prabir Pradhan678438e2023-04-13 19:32:51 +00004392 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004394
4395 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004396 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004397 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4398 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
Antonio Kantekf16f2832021-09-28 04:39:20 +00004402 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 { // acquire lock
4404 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004405 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4406 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4407 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004408 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004409 if (touchStateIt != mTouchStatesByDisplay.end()) {
4410 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004411 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004412 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4413 }
4414 }
4415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416
4417 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004418 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004419 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004420 displayTransform = it->second.transform;
4421 }
4422
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 mLock.unlock();
4424
4425 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004426 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4427 args.action, args.actionButton, args.flags, args.edgeFlags,
4428 args.metaState, args.buttonState, args.classification,
4429 displayTransform, args.xPrecision, args.yPrecision,
4430 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004431 args.downTime, args.eventTime, args.getPointerCount(),
4432 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
4434 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004435 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 return; // event was consumed by the filter
4437 }
4438
4439 mLock.lock();
4440 }
4441
4442 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004443 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004444 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4445 args.displayId, policyFlags, args.action,
4446 args.actionButton, args.flags, args.metaState,
4447 args.buttonState, args.classification, args.edgeFlags,
4448 args.xPrecision, args.yPrecision,
4449 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004450 args.downTime, args.getPointerCount(),
4451 args.pointerProperties.data(),
4452 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453
Prabir Pradhan678438e2023-04-13 19:32:51 +00004454 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4455 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004456 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004457 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4458 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004459 }
4460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004461 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 mLock.unlock();
4463 } // release lock
4464
4465 if (needWake) {
4466 mLooper->wake();
4467 }
4468}
4469
Prabir Pradhan678438e2023-04-13 19:32:51 +00004470void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004471 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004472 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4473 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004474 args.id, args.eventTime, args.deviceId, args.source,
4475 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 }
Chris Yef59a2f42020-10-16 12:55:26 -07004477
Antonio Kantekf16f2832021-09-28 04:39:20 +00004478 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004479 { // acquire lock
4480 mLock.lock();
4481
4482 // Just enqueue a new sensor event.
4483 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004484 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4485 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4486 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004487
4488 needWake = enqueueInboundEventLocked(std::move(newEntry));
4489 mLock.unlock();
4490 } // release lock
4491
4492 if (needWake) {
4493 mLooper->wake();
4494 }
4495}
4496
Prabir Pradhan678438e2023-04-13 19:32:51 +00004497void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004498 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004499 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4500 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004501 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004502 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004503}
4504
Prabir Pradhan678438e2023-04-13 19:32:51 +00004505bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004506 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507}
4508
Prabir Pradhan678438e2023-04-13 19:32:51 +00004509void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004510 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004511 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4512 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004513 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515
Prabir Pradhan678438e2023-04-13 19:32:51 +00004516 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004518 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519}
4520
Prabir Pradhan678438e2023-04-13 19:32:51 +00004521void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004522 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004523 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4524 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
Antonio Kantekf16f2832021-09-28 04:39:20 +00004527 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004529 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004531 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004532 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004533 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 } // release lock
4535
4536 if (needWake) {
4537 mLooper->wake();
4538 }
4539}
4540
Prabir Pradhan678438e2023-04-13 19:32:51 +00004541void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004542 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004543 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4544 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004545 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004546
Antonio Kantekf16f2832021-09-28 04:39:20 +00004547 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004548 { // acquire lock
4549 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004550 auto entry =
4551 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004552 needWake = enqueueInboundEventLocked(std::move(entry));
4553 } // release lock
4554
4555 if (needWake) {
4556 mLooper->wake();
4557 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004558}
4559
Prabir Pradhan5735a322022-04-11 17:23:34 +00004560InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004561 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004562 InputEventInjectionSync syncMode,
4563 std::chrono::milliseconds timeout,
4564 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004565 Result<void> eventValidation = validateInputEvent(*event);
4566 if (!eventValidation.ok()) {
4567 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4568 return InputEventInjectionResult::FAILED;
4569 }
4570
Prabir Pradhan65613802023-02-22 23:36:58 +00004571 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004572 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004573 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4574 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4575 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004576 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004577 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578
Prabir Pradhan5735a322022-04-11 17:23:34 +00004579 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004581 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004582 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4583 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4584 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4585 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4586 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004587 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004588 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004589 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004590 }
4591
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004592 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004594 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004595 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004596 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004597 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004598 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4599 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4600 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004601 int32_t keyCode = incomingKey.getKeyCode();
4602 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004603 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004605 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004606 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004607 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4608 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4609 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004611 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4612 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004613 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614
4615 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4616 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004617 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4619 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4620 std::to_string(t.duration().count()).c_str());
4621 }
4622 }
4623
4624 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004625 std::unique_ptr<KeyEntry> injectedEntry =
4626 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004627 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004628 incomingKey.getDisplayId(), policyFlags, action,
4629 flags, keyCode, incomingKey.getScanCode(), metaState,
4630 incomingKey.getRepeatCount(),
4631 incomingKey.getDownTime());
4632 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 }
4635
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004636 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004637 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004638 const bool isPointerEvent =
4639 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4640 // If a pointer event has no displayId specified, inject it to the default display.
4641 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4642 ? ADISPLAY_ID_DEFAULT
4643 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004644 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004645
4646 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004647 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004649 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4651 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4652 std::to_string(t.duration().count()).c_str());
4653 }
4654 }
4655
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004656 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4657 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4658 }
4659
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004660 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004661 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4662 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004663 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004664 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4665 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004666 displayId, policyFlags, motionEvent.getAction(),
4667 motionEvent.getActionButton(), flags,
4668 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004669 motionEvent.getButtonState(),
4670 motionEvent.getClassification(),
4671 motionEvent.getEdgeFlags(),
4672 motionEvent.getXPrecision(),
4673 motionEvent.getYPrecision(),
4674 motionEvent.getRawXCursorPosition(),
4675 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004676 motionEvent.getDownTime(),
4677 motionEvent.getPointerCount(),
4678 motionEvent.getPointerProperties(),
4679 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004680 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004681 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004682 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004683 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004684 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004685 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004686 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4687 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004688 displayId, policyFlags,
4689 motionEvent.getAction(),
4690 motionEvent.getActionButton(), flags,
4691 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004692 motionEvent.getButtonState(),
4693 motionEvent.getClassification(),
4694 motionEvent.getEdgeFlags(),
4695 motionEvent.getXPrecision(),
4696 motionEvent.getYPrecision(),
4697 motionEvent.getRawXCursorPosition(),
4698 motionEvent.getRawYCursorPosition(),
4699 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004700 motionEvent.getPointerCount(),
4701 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004702 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004703 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4704 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004705 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004706 }
4707 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004710 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004711 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004712 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 }
4714
Prabir Pradhan5735a322022-04-11 17:23:34 +00004715 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 injectionState->injectionIsAsync = true;
4718 }
4719
4720 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004721 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722
4723 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004724 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004725 if (DEBUG_INJECTION) {
4726 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4727 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004728 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004729 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 }
4731
4732 mLock.unlock();
4733
4734 if (needWake) {
4735 mLooper->wake();
4736 }
4737
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004738 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004740 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004742 if (syncMode == InputEventInjectionSync::NONE) {
4743 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 } else {
4745 for (;;) {
4746 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004747 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 break;
4749 }
4750
4751 nsecs_t remainingTimeout = endTime - now();
4752 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004753 if (DEBUG_INJECTION) {
4754 ALOGD("injectInputEvent - Timed out waiting for injection result "
4755 "to become available.");
4756 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004757 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 break;
4759 }
4760
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004761 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 }
4763
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004764 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4765 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004767 if (DEBUG_INJECTION) {
4768 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4769 injectionState->pendingForegroundDispatches);
4770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 nsecs_t remainingTimeout = endTime - now();
4772 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004773 if (DEBUG_INJECTION) {
4774 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4775 "dispatches to finish.");
4776 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004777 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 break;
4779 }
4780
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004781 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 }
4783 }
4784 }
4785
4786 injectionState->release();
4787 } // release lock
4788
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004789 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004790 LOG(DEBUG) << "injectInputEvent - Finished with result "
4791 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793
4794 return injectionResult;
4795}
4796
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004797std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004798 std::array<uint8_t, 32> calculatedHmac;
4799 std::unique_ptr<VerifiedInputEvent> result;
4800 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004801 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004802 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4803 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4804 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004805 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004806 break;
4807 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004808 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004809 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4810 VerifiedMotionEvent verifiedMotionEvent =
4811 verifiedMotionEventFromMotionEvent(motionEvent);
4812 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004813 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004814 break;
4815 }
4816 default: {
4817 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4818 return nullptr;
4819 }
4820 }
4821 if (calculatedHmac == INVALID_HMAC) {
4822 return nullptr;
4823 }
tyiu1573a672023-02-21 22:38:32 +00004824 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004825 return nullptr;
4826 }
4827 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004828}
4829
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004830void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004831 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004832 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004834 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004835 LOG(DEBUG) << "Setting input event injection result to "
4836 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004839 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 // Log the outcome since the injector did not wait for the injection result.
4841 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004842 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004843 ALOGV("Asynchronous input event injection succeeded.");
4844 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004845 case InputEventInjectionResult::TARGET_MISMATCH:
4846 ALOGV("Asynchronous input event injection target mismatch.");
4847 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004848 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 ALOGW("Asynchronous input event injection failed.");
4850 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004851 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004852 ALOGW("Asynchronous input event injection timed out.");
4853 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004854 case InputEventInjectionResult::PENDING:
4855 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4856 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858 }
4859
4860 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004861 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863}
4864
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004865void InputDispatcher::transformMotionEntryForInjectionLocked(
4866 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004867 // Input injection works in the logical display coordinate space, but the input pipeline works
4868 // display space, so we need to transform the injected events accordingly.
4869 const auto it = mDisplayInfos.find(entry.displayId);
4870 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004871 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004872
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004873 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4874 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4875 const vec2 cursor =
4876 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4877 {entry.xCursorPosition, entry.yCursorPosition});
4878 entry.xCursorPosition = cursor.x;
4879 entry.yCursorPosition = cursor.y;
4880 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004881 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004882 entry.pointerCoords[i] =
4883 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4884 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004885 }
4886}
4887
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004888void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4889 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 if (injectionState) {
4891 injectionState->pendingForegroundDispatches += 1;
4892 }
4893}
4894
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004895void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4896 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 if (injectionState) {
4898 injectionState->pendingForegroundDispatches -= 1;
4899
4900 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004901 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 }
4903 }
4904}
4905
chaviw98318de2021-05-19 16:45:23 -05004906const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004907 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004908 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004909 auto it = mWindowHandlesByDisplay.find(displayId);
4910 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004911}
4912
chaviw98318de2021-05-19 16:45:23 -05004913sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004914 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004915 if (windowHandleToken == nullptr) {
4916 return nullptr;
4917 }
4918
Arthur Hungb92218b2018-08-14 12:00:21 +08004919 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004920 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4921 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004922 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004923 return windowHandle;
4924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 }
4926 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004927 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928}
4929
chaviw98318de2021-05-19 16:45:23 -05004930sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4931 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004932 if (windowHandleToken == nullptr) {
4933 return nullptr;
4934 }
4935
chaviw98318de2021-05-19 16:45:23 -05004936 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004937 if (windowHandle->getToken() == windowHandleToken) {
4938 return windowHandle;
4939 }
4940 }
4941 return nullptr;
4942}
4943
chaviw98318de2021-05-19 16:45:23 -05004944sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4945 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004946 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004947 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4948 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004949 if (handle->getId() == windowHandle->getId() &&
4950 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004951 if (windowHandle->getInfo()->displayId != it.first) {
4952 ALOGE("Found window %s in display %" PRId32
4953 ", but it should belong to display %" PRId32,
4954 windowHandle->getName().c_str(), it.first,
4955 windowHandle->getInfo()->displayId);
4956 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004957 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004961 return nullptr;
4962}
4963
chaviw98318de2021-05-19 16:45:23 -05004964sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004965 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4966 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967}
4968
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004969ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4970 auto displayInfoIt = mDisplayInfos.find(displayId);
4971 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4972 : kIdentityTransform;
4973}
4974
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004975bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4976 const MotionEntry& motionEntry) const {
4977 const WindowInfo& info = *window->getInfo();
4978
4979 // Skip spy window targets that are not valid for targeted injection.
4980 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004981 return false;
4982 }
4983
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004984 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4985 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4986 return false;
4987 }
4988
4989 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4990 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4991 window->getName().c_str());
4992 return false;
4993 }
4994
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004995 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004996 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004997 ALOGW("Not sending touch to %s because there's no corresponding connection",
4998 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004999 return false;
5000 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005001
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005002 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005003 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005004 return false;
5005 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005006
5007 // Drop events that can't be trusted due to occlusion
5008 const auto [x, y] = resolveTouchedPosition(motionEntry);
5009 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5010 if (!isTouchTrustedLocked(occlusionInfo)) {
5011 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005012 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005013 for (const auto& log : occlusionInfo.debugInfo) {
5014 ALOGD("%s", log.c_str());
5015 }
5016 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005017 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5018 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005019 return false;
5020 }
5021
5022 // Drop touch events if requested by input feature
5023 if (shouldDropInput(motionEntry, window)) {
5024 return false;
5025 }
5026
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005027 return true;
5028}
5029
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005030std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5031 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005032 auto connectionIt = mConnectionsByToken.find(token);
5033 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005034 return nullptr;
5035 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005036 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005037}
5038
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005039void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005040 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5041 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005042 // Remove all handles on a display if there are no windows left.
5043 mWindowHandlesByDisplay.erase(displayId);
5044 return;
5045 }
5046
5047 // Since we compare the pointer of input window handles across window updates, we need
5048 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005049 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5050 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5051 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005052 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005053 }
5054
chaviw98318de2021-05-19 16:45:23 -05005055 std::vector<sp<WindowInfoHandle>> newHandles;
5056 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005057 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005058 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005059 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005060 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005061 const bool canReceiveInput =
5062 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5063 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005064 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005065 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005066 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005067 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005068 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005069 }
5070
5071 if (info->displayId != displayId) {
5072 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5073 handle->getName().c_str(), displayId, info->displayId);
5074 continue;
5075 }
5076
Robert Carredd13602020-04-13 17:24:34 -07005077 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5078 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005079 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005080 oldHandle->updateFrom(handle);
5081 newHandles.push_back(oldHandle);
5082 } else {
5083 newHandles.push_back(handle);
5084 }
5085 }
5086
5087 // Insert or replace
5088 mWindowHandlesByDisplay[displayId] = newHandles;
5089}
5090
Arthur Hung72d8dc32020-03-28 00:48:39 +00005091void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005092 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005093 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005094 { // acquire lock
5095 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005096 for (const auto& [displayId, handles] : handlesPerDisplay) {
5097 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005098 }
5099 }
5100 // Wake up poll loop since it may need to make new input dispatching choices.
5101 mLooper->wake();
5102}
5103
Arthur Hungb92218b2018-08-14 12:00:21 +08005104/**
5105 * Called from InputManagerService, update window handle list by displayId that can receive input.
5106 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5107 * If set an empty list, remove all handles from the specific display.
5108 * For focused handle, check if need to change and send a cancel event to previous one.
5109 * For removed handle, check if need to send a cancel event if already in touch.
5110 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005111void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005112 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005113 if (DEBUG_FOCUS) {
5114 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005115 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005116 windowList += iwh->getName() + " ";
5117 }
5118 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120
Prabir Pradhand65552b2021-10-07 11:23:50 -07005121 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005122 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005123 const WindowInfo& info = *window->getInfo();
5124
5125 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005126 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005127 if (noInputWindow && window->getToken() != nullptr) {
5128 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5129 window->getName().c_str());
5130 window->releaseChannel();
5131 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005132
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005133 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005134 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5135 !info.inputConfig.test(
5136 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005137 "%s has feature SPY, but is not a trusted overlay.",
5138 window->getName().c_str());
5139
Prabir Pradhand65552b2021-10-07 11:23:50 -07005140 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005141 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5142 !info.inputConfig.test(
5143 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005144 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5145 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005146 }
5147
Arthur Hung72d8dc32020-03-28 00:48:39 +00005148 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005149 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005151 // Save the old windows' orientation by ID before it gets updated.
5152 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005153 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005154 oldWindowOrientations.emplace(handle->getId(),
5155 handle->getInfo()->transform.getOrientation());
5156 }
5157
chaviw98318de2021-05-19 16:45:23 -05005158 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005159
chaviw98318de2021-05-19 16:45:23 -05005160 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005161
Vishnu Nairc519ff72021-01-21 08:23:08 -08005162 std::optional<FocusResolver::FocusChanges> changes =
5163 mFocusResolver.setInputWindows(displayId, windowHandles);
5164 if (changes) {
5165 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005168 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5169 mTouchStatesByDisplay.find(displayId);
5170 if (stateIt != mTouchStatesByDisplay.end()) {
5171 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005172 for (size_t i = 0; i < state.windows.size();) {
5173 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005174 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005175 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005176 ALOGD("Touched window was removed: %s in display %" PRId32,
5177 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005178 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005179 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005180 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5181 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005182 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005183 "touched window was removed");
5184 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005185 // Since we are about to drop the touch, cancel the events for the wallpaper as
5186 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005187 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005188 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5189 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005190 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005191 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005194 state.windows.erase(state.windows.begin() + i);
5195 } else {
5196 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 }
5198 }
arthurhungb89ccb02020-12-30 16:19:01 +08005199
arthurhung6d4bed92021-03-17 11:59:33 +08005200 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005201 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005202 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005203 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005204 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005205 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5206 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005207 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005208 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005209 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005210
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005211 // Determine if the orientation of any of the input windows have changed, and cancel all
5212 // pointer events if necessary.
5213 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5214 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5215 if (newWindowHandle != nullptr &&
5216 newWindowHandle->getInfo()->transform.getOrientation() !=
5217 oldWindowOrientations[oldWindowHandle->getId()]) {
5218 std::shared_ptr<InputChannel> inputChannel =
5219 getInputChannelLocked(newWindowHandle->getToken());
5220 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005221 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005222 "touched window's orientation changed");
5223 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005224 }
5225 }
5226 }
5227
Arthur Hung72d8dc32020-03-28 00:48:39 +00005228 // Release information for windows that are no longer present.
5229 // This ensures that unused input channels are released promptly.
5230 // Otherwise, they might stick around until the window handle is destroyed
5231 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005232 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005233 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005234 if (DEBUG_FOCUS) {
5235 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005236 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005237 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005238 }
chaviw291d88a2019-02-14 10:33:58 -08005239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240}
5241
5242void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005243 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005244 if (DEBUG_FOCUS) {
5245 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5246 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5247 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005249 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005250 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251 } // release lock
5252
5253 // Wake up poll loop since it may need to make new input dispatching choices.
5254 mLooper->wake();
5255}
5256
Vishnu Nair599f1412021-06-21 10:39:58 -07005257void InputDispatcher::setFocusedApplicationLocked(
5258 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5259 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5260 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5261
5262 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5263 return; // This application is already focused. No need to wake up or change anything.
5264 }
5265
5266 // Set the new application handle.
5267 if (inputApplicationHandle != nullptr) {
5268 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5269 } else {
5270 mFocusedApplicationHandlesByDisplay.erase(displayId);
5271 }
5272
5273 // No matter what the old focused application was, stop waiting on it because it is
5274 // no longer focused.
5275 resetNoFocusedWindowTimeoutLocked();
5276}
5277
Tiger Huang721e26f2018-07-24 22:26:19 +08005278/**
5279 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5280 * the display not specified.
5281 *
5282 * We track any unreleased events for each window. If a window loses the ability to receive the
5283 * released event, we will send a cancel event to it. So when the focused display is changed, we
5284 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5285 * display. The display-specified events won't be affected.
5286 */
5287void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005288 if (DEBUG_FOCUS) {
5289 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5290 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005291 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005292 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005293
5294 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005295 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005296 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005297 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005298 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005299 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005300 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005301 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005302 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005303 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005304 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005305 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5306 }
5307 }
5308 mFocusedDisplayId = displayId;
5309
Chris Ye3c2d6f52020-08-09 10:39:48 -07005310 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005311 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005312 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005313
Vishnu Nairad321cd2020-08-20 16:40:21 -07005314 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005315 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005316 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005317 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005318 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005319 }
5320 }
5321 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005322 } // release lock
5323
5324 // Wake up poll loop since it may need to make new input dispatching choices.
5325 mLooper->wake();
5326}
5327
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005329 if (DEBUG_FOCUS) {
5330 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
5333 bool changed;
5334 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005335 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336
5337 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5338 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005339 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 }
5341
5342 if (mDispatchEnabled && !enabled) {
5343 resetAndDropEverythingLocked("dispatcher is being disabled");
5344 }
5345
5346 mDispatchEnabled = enabled;
5347 mDispatchFrozen = frozen;
5348 changed = true;
5349 } else {
5350 changed = false;
5351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352 } // release lock
5353
5354 if (changed) {
5355 // Wake up poll loop since it may need to make new input dispatching choices.
5356 mLooper->wake();
5357 }
5358}
5359
5360void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005361 if (DEBUG_FOCUS) {
5362 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364
5365 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005366 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367
5368 if (mInputFilterEnabled == enabled) {
5369 return;
5370 }
5371
5372 mInputFilterEnabled = enabled;
5373 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5374 } // release lock
5375
5376 // Wake up poll loop since there might be work to do to drop everything.
5377 mLooper->wake();
5378}
5379
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005380bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005381 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005382 bool needWake = false;
5383 {
5384 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005385 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005386 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005387 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005388 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5389 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005390 mTouchModePerDisplay.count(displayId) == 0
5391 ? "not set"
5392 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5393
Antonio Kantek15beb512022-06-13 22:35:41 +00005394 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5395 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005396 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005397 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005398 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005399 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5400 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005401 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005402 "window nor none of the previously interacted window",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005403 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005404 return false;
5405 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005406 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005407 mTouchModePerDisplay[displayId] = inTouchMode;
5408 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5409 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005410 needWake = enqueueInboundEventLocked(std::move(entry));
5411 } // release lock
5412
5413 if (needWake) {
5414 mLooper->wake();
5415 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005416 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005417}
5418
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005419bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005420 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5421 if (focusedToken == nullptr) {
5422 return false;
5423 }
5424 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5425 return isWindowOwnedBy(windowHandle, pid, uid);
5426}
5427
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005428bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005429 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5430 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5431 const sp<WindowInfoHandle> windowHandle =
5432 getWindowHandleLocked(connectionToken);
5433 return isWindowOwnedBy(windowHandle, pid, uid);
5434 }) != mInteractionConnectionTokens.end();
5435}
5436
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005437void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5438 if (opacity < 0 || opacity > 1) {
5439 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5440 return;
5441 }
5442
5443 std::scoped_lock lock(mLock);
5444 mMaximumObscuringOpacityForTouch = opacity;
5445}
5446
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005447std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5448InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005449 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5450 for (TouchedWindow& w : state.windows) {
5451 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005452 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005453 }
5454 }
5455 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005456 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005457}
5458
arthurhungb89ccb02020-12-30 16:19:01 +08005459bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5460 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005461 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005462 if (DEBUG_FOCUS) {
5463 ALOGD("Trivial transfer to same window.");
5464 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005465 return true;
5466 }
5467
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470
Arthur Hungabbb9d82021-09-01 14:52:30 +00005471 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005472 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005473
Arthur Hungabbb9d82021-09-01 14:52:30 +00005474 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005475 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 return false;
5477 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005478 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5479 if (deviceIds.size() != 1) {
5480 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5481 << " for window: " << touchedWindow->dump();
5482 return false;
5483 }
5484 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005485
Arthur Hungabbb9d82021-09-01 14:52:30 +00005486 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5487 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005488 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005489 return false;
5490 }
5491
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005492 if (DEBUG_FOCUS) {
5493 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005494 touchedWindow->windowHandle->getName().c_str(),
5495 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 }
5497
Arthur Hungabbb9d82021-09-01 14:52:30 +00005498 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005499 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005500 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005501 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005502 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503
Arthur Hungabbb9d82021-09-01 14:52:30 +00005504 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005505 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005506 ftl::Flags<InputTarget::Flags> newTargetFlags =
5507 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005508 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005509 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005510 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005511 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5512 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513
Arthur Hungabbb9d82021-09-01 14:52:30 +00005514 // Store the dragging window.
5515 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005516 if (pointerIds.count() != 1) {
5517 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5518 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005519 return false;
5520 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005521 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005522 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005523 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 }
5525
Arthur Hungabbb9d82021-09-01 14:52:30 +00005526 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005527 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5528 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005529 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005530 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005531 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5532 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005534 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5535 newTargetFlags);
5536
5537 // Check if the wallpaper window should deliver the corresponding event.
5538 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005539 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 } // release lock
5542
5543 // Wake up poll loop since it may need to make new input dispatching choices.
5544 mLooper->wake();
5545 return true;
5546}
5547
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005548/**
5549 * Get the touched foreground window on the given display.
5550 * Return null if there are no windows touched on that display, or if more than one foreground
5551 * window is being touched.
5552 */
5553sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5554 auto stateIt = mTouchStatesByDisplay.find(displayId);
5555 if (stateIt == mTouchStatesByDisplay.end()) {
5556 ALOGI("No touch state on display %" PRId32, displayId);
5557 return nullptr;
5558 }
5559
5560 const TouchState& state = stateIt->second;
5561 sp<WindowInfoHandle> touchedForegroundWindow;
5562 // If multiple foreground windows are touched, return nullptr
5563 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005564 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005565 if (touchedForegroundWindow != nullptr) {
5566 ALOGI("Two or more foreground windows: %s and %s",
5567 touchedForegroundWindow->getName().c_str(),
5568 window.windowHandle->getName().c_str());
5569 return nullptr;
5570 }
5571 touchedForegroundWindow = window.windowHandle;
5572 }
5573 }
5574 return touchedForegroundWindow;
5575}
5576
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005577// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005578bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005579 sp<IBinder> fromToken;
5580 { // acquire lock
5581 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005582 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005583 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005584 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5585 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005586 return false;
5587 }
5588
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005589 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5590 if (from == nullptr) {
5591 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5592 return false;
5593 }
5594
5595 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005596 } // release lock
5597
5598 return transferTouchFocus(fromToken, destChannelToken);
5599}
5600
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005602 if (DEBUG_FOCUS) {
5603 ALOGD("Resetting and dropping all events (%s).", reason);
5604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605
Michael Wrightfb04fd52022-11-24 22:31:11 +00005606 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 synthesizeCancelationEventsForAllConnectionsLocked(options);
5608
5609 resetKeyRepeatLocked();
5610 releasePendingEventLocked();
5611 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005612 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005614 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005615 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005616 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617}
5618
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005619void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005620 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 dumpDispatchStateLocked(dump);
5622
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005623 std::istringstream stream(dump);
5624 std::string line;
5625
5626 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005627 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 }
5629}
5630
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005631std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005632 std::string dump;
5633
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005634 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5635 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005636
5637 std::string windowName = "None";
5638 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005639 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005640 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5641 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5642 : "token has capture without window";
5643 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005644 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005645
5646 return dump;
5647}
5648
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005649void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005650 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5651 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5652 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005653 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654
Tiger Huang721e26f2018-07-24 22:26:19 +08005655 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5656 dump += StringPrintf(INDENT "FocusedApplications:\n");
5657 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5658 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005659 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005660 const std::chrono::duration timeout =
5661 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005662 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005663 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005664 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005667 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005669
Vishnu Nairc519ff72021-01-21 08:23:08 -08005670 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005671 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005673 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005674 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005675 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005676 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5677 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 }
5679 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005680 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 }
5682
arthurhung6d4bed92021-03-17 11:59:33 +08005683 if (mDragState) {
5684 dump += StringPrintf(INDENT "DragState:\n");
5685 mDragState->dump(dump, INDENT2);
5686 }
5687
Arthur Hungb92218b2018-08-14 12:00:21 +08005688 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005689 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5690 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5691 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5692 const auto& displayInfo = it->second;
5693 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5694 displayInfo.logicalHeight);
5695 displayInfo.transform.dump(dump, "transform", INDENT4);
5696 } else {
5697 dump += INDENT2 "No DisplayInfo found!\n";
5698 }
5699
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005700 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005701 dump += INDENT2 "Windows:\n";
5702 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005703 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5704 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005706 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005707 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005708 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005709 "applicationInfo.name=%s, "
5710 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005711 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005712 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005713 windowInfo->displayId,
5714 windowInfo->inputConfig.string().c_str(),
5715 windowInfo->alpha, windowInfo->frameLeft,
5716 windowInfo->frameTop, windowInfo->frameRight,
5717 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005718 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005719 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005720 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005721 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005722 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005723 "touchOcclusionMode=%s\n",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005724 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005725 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005726 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005727 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005728 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005729 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005730 }
5731 } else {
5732 dump += INDENT2 "Windows: <none>\n";
5733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005734 }
5735 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005736 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 }
5738
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005739 if (!mGlobalMonitorsByDisplay.empty()) {
5740 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5741 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005742 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005745 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746 }
5747
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005748 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749
5750 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005751 if (!mRecentQueue.empty()) {
5752 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005753 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005754 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005755 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005756 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757 }
5758 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005759 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 }
5761
5762 // Dump event currently being dispatched.
5763 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005764 dump += INDENT "PendingEvent:\n";
5765 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005766 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005767 dump += StringPrintf(", age=%" PRId64 "ms\n",
5768 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005770 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 }
5772
5773 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005774 if (!mInboundQueue.empty()) {
5775 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005776 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005777 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005778 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005779 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005782 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005785 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005787 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005788 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005789 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005790 }
5791 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005792 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005793 }
5794
Prabir Pradhancef936d2021-07-21 16:17:52 +00005795 if (!mCommandQueue.empty()) {
5796 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5797 } else {
5798 dump += INDENT "CommandQueue: <empty>\n";
5799 }
5800
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005801 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005802 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005803 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005804 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005805 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005806 connection->inputChannel->getFd().get(),
5807 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005808 connection->getWindowName().c_str(),
5809 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005810 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005812 if (!connection->outboundQueue.empty()) {
5813 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5814 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005815 dump += dumpQueue(connection->outboundQueue, currentTime);
5816
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005818 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819 }
5820
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005821 if (!connection->waitQueue.empty()) {
5822 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5823 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005824 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005826 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 }
5828 }
5829 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005830 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 }
5832
5833 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005834 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5835 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005837 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838 }
5839
Antonio Kantek15beb512022-06-13 22:35:41 +00005840 if (!mTouchModePerDisplay.empty()) {
5841 dump += INDENT "TouchModePerDisplay:\n";
5842 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5843 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5844 std::to_string(touchMode).c_str());
5845 }
5846 } else {
5847 dump += INDENT "TouchModePerDisplay: <none>\n";
5848 }
5849
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005850 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005851 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5852 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5853 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005854 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005855 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856}
5857
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005858void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005859 const size_t numMonitors = monitors.size();
5860 for (size_t i = 0; i < numMonitors; i++) {
5861 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005862 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005863 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5864 dump += "\n";
5865 }
5866}
5867
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005868class LooperEventCallback : public LooperCallback {
5869public:
5870 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5871 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5872
5873private:
5874 std::function<int(int events)> mCallback;
5875};
5876
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005877Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005878 if (DEBUG_CHANNEL_CREATION) {
5879 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005882 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005883 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005884 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005885
5886 if (result) {
5887 return base::Error(result) << "Failed to open input channel pair with name " << name;
5888 }
5889
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005891 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005892 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005893 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005894 std::shared_ptr<Connection> connection =
5895 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5896 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005898 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5899 ALOGE("Created a new connection, but the token %p is already known", token.get());
5900 }
5901 mConnectionsByToken.emplace(token, connection);
5902
5903 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5904 this, std::placeholders::_1, token);
5905
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005906 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5907 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 } // release lock
5909
5910 // Wake the looper because some connections have changed.
5911 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005912 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913}
5914
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005915Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005916 const std::string& name,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005917 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005918 std::shared_ptr<InputChannel> serverChannel;
5919 std::unique_ptr<InputChannel> clientChannel;
5920 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5921 if (result) {
5922 return base::Error(result) << "Failed to open input channel pair with name " << name;
5923 }
5924
Michael Wright3dd60e22019-03-27 22:06:44 +00005925 { // acquire lock
5926 std::scoped_lock _l(mLock);
5927
5928 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005929 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5930 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005931 }
5932
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005933 std::shared_ptr<Connection> connection =
5934 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005935 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005936 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005937
5938 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5939 ALOGE("Created a new connection, but the token %p is already known", token.get());
5940 }
5941 mConnectionsByToken.emplace(token, connection);
5942 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5943 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005944
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005945 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005946
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005947 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5948 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005949 }
Garfield Tan15601662020-09-22 15:32:38 -07005950
Michael Wright3dd60e22019-03-27 22:06:44 +00005951 // Wake the looper because some connections have changed.
5952 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005953 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005954}
5955
Garfield Tan15601662020-09-22 15:32:38 -07005956status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005958 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
Harry Cutts33476232023-01-30 19:57:29 +00005960 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 if (status) {
5962 return status;
5963 }
5964 } // release lock
5965
5966 // Wake the poll loop because removing the connection may have changed the current
5967 // synchronization state.
5968 mLooper->wake();
5969 return OK;
5970}
5971
Garfield Tan15601662020-09-22 15:32:38 -07005972status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5973 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005974 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005975 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005976 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 return BAD_VALUE;
5978 }
5979
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005980 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005981
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005983 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984 }
5985
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005986 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987
5988 nsecs_t currentTime = now();
5989 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5990
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005991 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992 return OK;
5993}
5994
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005995void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005996 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5997 auto& [displayId, monitors] = *it;
5998 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5999 return monitor.inputChannel->getConnectionToken() == connectionToken;
6000 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006001
Michael Wright3dd60e22019-03-27 22:06:44 +00006002 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006003 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006004 } else {
6005 ++it;
6006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007 }
6008}
6009
Michael Wright3dd60e22019-03-27 22:06:44 +00006010status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006012 return pilferPointersLocked(token);
6013}
Michael Wright3dd60e22019-03-27 22:06:44 +00006014
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006015status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006016 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6017 if (!requestingChannel) {
6018 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
6019 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006020 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006021
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006022 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006023 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006024 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
6025 " Ignoring.");
6026 return BAD_VALUE;
6027 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006028 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
6029 if (deviceIds.size() != 1) {
6030 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
6031 << " in window: " << windowPtr->dump();
6032 return BAD_VALUE;
6033 }
6034 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006035
6036 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006037 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006038 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00006039 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006040 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006041 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006042 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006043 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6044 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006045 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006046 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006047 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006048 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006049 if (channel != nullptr && channel->getConnectionToken() != token) {
6050 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6051 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6052 canceledWindows += channel->getName();
6053 }
6054 }
6055 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6056 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6057 canceledWindows.c_str());
6058
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006059 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006060 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006061 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006062
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006063 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006064 return OK;
6065}
6066
Prabir Pradhan99987712020-11-10 18:43:05 -08006067void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6068 { // acquire lock
6069 std::scoped_lock _l(mLock);
6070 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006071 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006072 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6073 windowHandle != nullptr ? windowHandle->getName().c_str()
6074 : "token without window");
6075 }
6076
Vishnu Nairc519ff72021-01-21 08:23:08 -08006077 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006078 if (focusedToken != windowToken) {
6079 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6080 enabled ? "enable" : "disable");
6081 return;
6082 }
6083
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006084 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006085 ALOGW("Ignoring request to %s Pointer Capture: "
6086 "window has %s requested pointer capture.",
6087 enabled ? "enable" : "disable", enabled ? "already" : "not");
6088 return;
6089 }
6090
Christine Franksb768bb42021-11-29 12:11:31 -08006091 if (enabled) {
6092 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6093 mIneligibleDisplaysForPointerCapture.end(),
6094 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6095 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6096 return;
6097 }
6098 }
6099
Prabir Pradhan99987712020-11-10 18:43:05 -08006100 setPointerCaptureLocked(enabled);
6101 } // release lock
6102
6103 // Wake the thread to process command entries.
6104 mLooper->wake();
6105}
6106
Christine Franksb768bb42021-11-29 12:11:31 -08006107void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6108 { // acquire lock
6109 std::scoped_lock _l(mLock);
6110 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6111 if (!isEligible) {
6112 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6113 }
6114 } // release lock
6115}
6116
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006117std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006118 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006119 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006120 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006121 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006122 }
6123 }
6124 }
6125 return std::nullopt;
6126}
6127
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006128std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6129 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006130 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006131 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006132 }
6133
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006134 for (const auto& [token, connection] : mConnectionsByToken) {
6135 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006136 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006137 }
6138 }
Robert Carr4e670e52018-08-15 13:26:12 -07006139
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006140 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141}
6142
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006143std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006144 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006145 if (connection == nullptr) {
6146 return "<nullptr>";
6147 }
6148 return connection->getInputChannelName();
6149}
6150
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006151void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006152 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006153 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006154}
6155
Prabir Pradhancef936d2021-07-21 16:17:52 +00006156void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006157 const std::shared_ptr<Connection>& connection,
6158 uint32_t seq, bool handled,
6159 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160 // Handle post-event policy actions.
6161 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6162 if (dispatchEntryIt == connection->waitQueue.end()) {
6163 return;
6164 }
6165 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6166 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6167 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6168 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6169 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6170 }
6171 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6172 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6173 connection->inputChannel->getConnectionToken(),
6174 dispatchEntry->deliveryTime, consumeTime, finishTime);
6175 }
6176
6177 bool restartEvent;
6178 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6179 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6180 restartEvent =
6181 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6182 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6183 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6184 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6185 handled);
6186 } else {
6187 restartEvent = false;
6188 }
6189
6190 // Dequeue the event and start the next cycle.
6191 // Because the lock might have been released, it is possible that the
6192 // contents of the wait queue to have been drained, so we need to double-check
6193 // a few things.
6194 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6195 if (dispatchEntryIt != connection->waitQueue.end()) {
6196 dispatchEntry = *dispatchEntryIt;
6197 connection->waitQueue.erase(dispatchEntryIt);
6198 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6199 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6200 if (!connection->responsive) {
6201 connection->responsive = isConnectionResponsive(*connection);
6202 if (connection->responsive) {
6203 // The connection was unresponsive, and now it's responsive.
6204 processConnectionResponsiveLocked(*connection);
6205 }
6206 }
6207 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006208 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006209 connection->outboundQueue.push_front(dispatchEntry);
6210 traceOutboundQueueLength(*connection);
6211 } else {
6212 releaseDispatchEntry(dispatchEntry);
6213 }
6214 }
6215
6216 // Start the next dispatch cycle for this connection.
6217 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218}
6219
Prabir Pradhancef936d2021-07-21 16:17:52 +00006220void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6221 const sp<IBinder>& newToken) {
6222 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6223 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006224 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006225 };
6226 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227}
6228
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6230 auto command = [this, token, x, y]() REQUIRES(mLock) {
6231 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006232 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006233 };
6234 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006235}
6236
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006237void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006238 if (connection == nullptr) {
6239 LOG_ALWAYS_FATAL("Caller must check for nullness");
6240 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006241 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6242 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006243 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006244 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006245 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006246 return;
6247 }
6248 /**
6249 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6250 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6251 * has changed. This could cause newer entries to time out before the already dispatched
6252 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6253 * processes the events linearly. So providing information about the oldest entry seems to be
6254 * most useful.
6255 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006256 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006257 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6258 std::string reason =
6259 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006260 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006261 ns2ms(currentWait),
6262 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006263 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006264 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006265
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006266 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6267
6268 // Stop waking up for events on this connection, it is already unresponsive
6269 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006270}
6271
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006272void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6273 std::string reason =
6274 StringPrintf("%s does not have a focused window", application->getName().c_str());
6275 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006276
Yabin Cui8eb9c552023-06-08 18:05:07 +00006277 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006278 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006279 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280 };
6281 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006282}
6283
chaviw98318de2021-05-19 16:45:23 -05006284void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006285 const std::string& reason) {
6286 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6287 updateLastAnrStateLocked(windowLabel, reason);
6288}
6289
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006290void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6291 const std::string& reason) {
6292 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006293 updateLastAnrStateLocked(windowLabel, reason);
6294}
6295
6296void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6297 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006299 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 struct tm tm;
6301 localtime_r(&t, &tm);
6302 char timestr[64];
6303 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006304 mLastAnrState.clear();
6305 mLastAnrState += INDENT "ANR:\n";
6306 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006307 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6308 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006309 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006310}
6311
Prabir Pradhancef936d2021-07-21 16:17:52 +00006312void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6313 KeyEntry& entry) {
6314 const KeyEvent event = createKeyEvent(entry);
6315 nsecs_t delay = 0;
6316 { // release lock
6317 scoped_unlock unlock(mLock);
6318 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006319 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006320 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6321 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6322 std::to_string(t.duration().count()).c_str());
6323 }
6324 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006325
6326 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006327 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006328 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006329 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006331 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006332 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334}
6335
Prabir Pradhancef936d2021-07-21 16:17:52 +00006336void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006337 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006338 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006339 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006340 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006341 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006342 };
6343 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006344}
6345
Prabir Pradhanedd96402022-02-15 01:46:16 -08006346void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006347 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006348 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006349 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006350 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006351 };
6352 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006353}
6354
6355/**
6356 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6357 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6358 * command entry to the command queue.
6359 */
6360void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6361 std::string reason) {
6362 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006363 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006364 if (connection.monitor) {
6365 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6366 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006367 pid = findMonitorPidByTokenLocked(connectionToken);
6368 } else {
6369 // The connection is a window
6370 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6371 reason.c_str());
6372 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6373 if (handle != nullptr) {
6374 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006375 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006376 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006377 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006378}
6379
6380/**
6381 * Tell the policy that a connection has become responsive so that it can stop ANR.
6382 */
6383void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6384 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006385 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006386 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006387 pid = findMonitorPidByTokenLocked(connectionToken);
6388 } else {
6389 // The connection is a window
6390 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6391 if (handle != nullptr) {
6392 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006393 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006394 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006395 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006396}
6397
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006398bool InputDispatcher::afterKeyEventLockedInterruptable(
6399 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6400 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006401 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006402 if (!handled) {
6403 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006404 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006405 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006406 return false;
6407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006409 // Get the fallback key state.
6410 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006411 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006412 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006413 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006414 connection->inputState.removeFallbackKey(originalKeyCode);
6415 }
6416
6417 if (handled || !dispatchEntry->hasForegroundTarget()) {
6418 // If the application handles the original key for which we previously
6419 // generated a fallback or if the window is not a foreground window,
6420 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006421 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006422 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006423 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6424 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6425 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6426 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6427 keyEntry.policyFlags);
6428 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006429 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006430 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006431
6432 mLock.unlock();
6433
Prabir Pradhana41d2442023-04-20 21:30:40 +00006434 if (const auto unhandledKeyFallback =
6435 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6436 event, keyEntry.policyFlags);
6437 unhandledKeyFallback) {
6438 event = *unhandledKeyFallback;
6439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440
6441 mLock.lock();
6442
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006443 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006445 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006446 "application handled the original non-fallback key "
6447 "or is no longer a foreground target, "
6448 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006449 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006450 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 connection->inputState.removeFallbackKey(originalKeyCode);
6453 }
6454 } else {
6455 // If the application did not handle a non-fallback key, first check
6456 // that we are in a good state to perform unhandled key event processing
6457 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006458 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006459 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006460 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6461 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6462 "since this is not an initial down. "
6463 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6464 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6465 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006466 return false;
6467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006468
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006469 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006470 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6471 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6472 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6473 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6474 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006475 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476
6477 mLock.unlock();
6478
Prabir Pradhana41d2442023-04-20 21:30:40 +00006479 bool fallback = false;
6480 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6481 event, keyEntry.policyFlags);
6482 fb) {
6483 fallback = true;
6484 event = *fb;
6485 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486
6487 mLock.lock();
6488
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006489 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 connection->inputState.removeFallbackKey(originalKeyCode);
6491 return false;
6492 }
6493
6494 // Latch the fallback keycode for this key on an initial down.
6495 // The fallback keycode cannot change at any other point in the lifecycle.
6496 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006497 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006498 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006500 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006502 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 }
6504
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006505 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006506
6507 // Cancel the fallback key if the policy decides not to send it anymore.
6508 // We will continue to dispatch the key to the policy but we will no
6509 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006510 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6511 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006512 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6513 if (fallback) {
6514 ALOGD("Unhandled key event: Policy requested to send key %d"
6515 "as a fallback for %d, but on the DOWN it had requested "
6516 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006517 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006518 } else {
6519 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6520 "but on the DOWN it had requested to send %d. "
6521 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006522 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006523 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006525
Michael Wrightfb04fd52022-11-24 22:31:11 +00006526 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006527 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006528 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006529 synthesizeCancelationEventsForConnectionLocked(connection, options);
6530
6531 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006533 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006534 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006535 }
6536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006538 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6539 {
6540 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006541 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006542 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006543 for (const auto& [key, value] : fallbackKeys) {
6544 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006545 }
6546 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6547 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006549 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006550
6551 if (fallback) {
6552 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006553 keyEntry.eventTime = event.getEventTime();
6554 keyEntry.deviceId = event.getDeviceId();
6555 keyEntry.source = event.getSource();
6556 keyEntry.displayId = event.getDisplayId();
6557 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006558 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006559 keyEntry.scanCode = event.getScanCode();
6560 keyEntry.metaState = event.getMetaState();
6561 keyEntry.repeatCount = event.getRepeatCount();
6562 keyEntry.downTime = event.getDownTime();
6563 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006564
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6566 ALOGD("Unhandled key event: Dispatching fallback key. "
6567 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006568 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006569 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006570 return true; // restart the event
6571 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006572 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6573 ALOGD("Unhandled key event: No fallback key.");
6574 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006575
6576 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006577 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578 }
6579 }
6580 return false;
6581}
6582
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006583bool InputDispatcher::afterMotionEventLockedInterruptable(
6584 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6585 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586 return false;
6587}
6588
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589void InputDispatcher::traceInboundQueueLengthLocked() {
6590 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006591 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 }
6593}
6594
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006595void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006596 if (ATRACE_ENABLED()) {
6597 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006598 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6599 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006600 }
6601}
6602
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006603void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 if (ATRACE_ENABLED()) {
6605 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006606 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6607 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608 }
6609}
6610
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006611void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006612 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006614 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 dumpDispatchStateLocked(dump);
6616
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006617 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006618 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006619 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620 }
6621}
6622
6623void InputDispatcher::monitor() {
6624 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006625 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006626 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006627 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628}
6629
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006630/**
6631 * Wake up the dispatcher and wait until it processes all events and commands.
6632 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6633 * this method can be safely called from any thread, as long as you've ensured that
6634 * the work you are interested in completing has already been queued.
6635 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006636bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006637 /**
6638 * Timeout should represent the longest possible time that a device might spend processing
6639 * events and commands.
6640 */
6641 constexpr std::chrono::duration TIMEOUT = 100ms;
6642 std::unique_lock lock(mLock);
6643 mLooper->wake();
6644 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6645 return result == std::cv_status::no_timeout;
6646}
6647
Vishnu Naire798b472020-07-23 13:52:21 -07006648/**
6649 * Sets focus to the window identified by the token. This must be called
6650 * after updating any input window handles.
6651 *
6652 * Params:
6653 * request.token - input channel token used to identify the window that should gain focus.
6654 * request.focusedToken - the token that the caller expects currently to be focused. If the
6655 * specified token does not match the currently focused window, this request will be dropped.
6656 * If the specified focused token matches the currently focused window, the call will succeed.
6657 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6658 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6659 * when requesting the focus change. This determines which request gets
6660 * precedence if there is a focus change request from another source such as pointer down.
6661 */
Vishnu Nair958da932020-08-21 17:12:37 -07006662void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6663 { // acquire lock
6664 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006665 std::optional<FocusResolver::FocusChanges> changes =
6666 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6667 if (changes) {
6668 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006669 }
6670 } // release lock
6671 // Wake up poll loop since it may need to make new input dispatching choices.
6672 mLooper->wake();
6673}
6674
Vishnu Nairc519ff72021-01-21 08:23:08 -08006675void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6676 if (changes.oldFocus) {
6677 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006678 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006679 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006680 "focus left window");
6681 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006682 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006683 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006684 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006685 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006686 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006687 }
6688
Prabir Pradhan99987712020-11-10 18:43:05 -08006689 // If a window has pointer capture, then it must have focus. We need to ensure that this
6690 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6691 // If the window loses focus before it loses pointer capture, then the window can be in a state
6692 // where it has pointer capture but not focus, violating the contract. Therefore we must
6693 // dispatch the pointer capture event before the focus event. Since focus events are added to
6694 // the front of the queue (above), we add the pointer capture event to the front of the queue
6695 // after the focus events are added. This ensures the pointer capture event ends up at the
6696 // front.
6697 disablePointerCaptureForcedLocked();
6698
Vishnu Nairc519ff72021-01-21 08:23:08 -08006699 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006700 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006701 }
6702}
Vishnu Nair958da932020-08-21 17:12:37 -07006703
Prabir Pradhan99987712020-11-10 18:43:05 -08006704void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006705 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006706 return;
6707 }
6708
6709 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6710
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006711 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006712 setPointerCaptureLocked(false);
6713 }
6714
6715 if (!mWindowTokenWithPointerCapture) {
6716 // No need to send capture changes because no window has capture.
6717 return;
6718 }
6719
6720 if (mPendingEvent != nullptr) {
6721 // Move the pending event to the front of the queue. This will give the chance
6722 // for the pending event to be dropped if it is a captured event.
6723 mInboundQueue.push_front(mPendingEvent);
6724 mPendingEvent = nullptr;
6725 }
6726
6727 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006728 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006729 mInboundQueue.push_front(std::move(entry));
6730}
6731
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006732void InputDispatcher::setPointerCaptureLocked(bool enable) {
6733 mCurrentPointerCaptureRequest.enable = enable;
6734 mCurrentPointerCaptureRequest.seq++;
6735 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006736 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006737 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006738 };
6739 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006740}
6741
Vishnu Nair599f1412021-06-21 10:39:58 -07006742void InputDispatcher::displayRemoved(int32_t displayId) {
6743 { // acquire lock
6744 std::scoped_lock _l(mLock);
6745 // Set an empty list to remove all handles from the specific display.
6746 setInputWindowsLocked(/* window handles */ {}, displayId);
6747 setFocusedApplicationLocked(displayId, nullptr);
6748 // Call focus resolver to clean up stale requests. This must be called after input windows
6749 // have been removed for the removed display.
6750 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006751 // Reset pointer capture eligibility, regardless of previous state.
6752 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006753 // Remove the associated touch mode state.
6754 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006755 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006756 } // release lock
6757
6758 // Wake up poll loop since it may need to make new input dispatching choices.
6759 mLooper->wake();
6760}
6761
Patrick Williamsd828f302023-04-28 17:52:08 -05006762void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006763 // The listener sends the windows as a flattened array. Separate the windows by display for
6764 // more convenient parsing.
6765 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006766 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006767 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006768 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006769 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006770
6771 { // acquire lock
6772 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006773
6774 // Ensure that we have an entry created for all existing displays so that if a displayId has
6775 // no windows, we can tell that the windows were removed from the display.
6776 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6777 handlesPerDisplay[displayId];
6778 }
6779
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006780 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006781 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006782 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6783 }
6784
6785 for (const auto& [displayId, handles] : handlesPerDisplay) {
6786 setInputWindowsLocked(handles, displayId);
6787 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006788
6789 if (update.vsyncId < mWindowInfosVsyncId) {
6790 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6791 ", current update vsync id: %" PRId64,
6792 mWindowInfosVsyncId, update.vsyncId);
6793 }
6794 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006795 }
6796 // Wake up poll loop since it may need to make new input dispatching choices.
6797 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006798}
6799
Vishnu Nair062a8672021-09-03 16:07:44 -07006800bool InputDispatcher::shouldDropInput(
6801 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006802 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6803 (windowHandle->getInfo()->inputConfig.test(
6804 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006805 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006806 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6807 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006808 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006809 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006810 windowHandle->getInfo()->displayId);
6811 return true;
6812 }
6813 return false;
6814}
6815
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006816void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006817 const gui::WindowInfosUpdate& update) {
6818 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006819}
6820
Arthur Hungdfd528e2021-12-08 13:23:04 +00006821void InputDispatcher::cancelCurrentTouch() {
6822 {
6823 std::scoped_lock _l(mLock);
6824 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006825 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006826 "cancel current touch");
6827 synthesizeCancelationEventsForAllConnectionsLocked(options);
6828
6829 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006830 }
6831 // Wake up poll loop since there might be work to do.
6832 mLooper->wake();
6833}
6834
Prabir Pradhan87112a72023-04-20 19:13:39 +00006835void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006836 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006837
6838 std::scoped_lock _l(mLock);
6839 mConfig = config;
6840}
6841
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006842void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6843 std::scoped_lock _l(mLock);
6844 mMonitorDispatchingTimeout = timeout;
6845}
6846
Arthur Hungc539dbb2022-12-08 07:45:36 +00006847void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6848 const sp<WindowInfoHandle>& oldWindowHandle,
6849 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006850 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006851 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006852 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6853 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006854 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6855 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6856 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6857 newWindowHandle->getInfo()->inputConfig.test(
6858 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6859 const sp<WindowInfoHandle> oldWallpaper =
6860 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6861 const sp<WindowInfoHandle> newWallpaper =
6862 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6863 if (oldWallpaper == newWallpaper) {
6864 return;
6865 }
6866
6867 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006868 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6869 addWindowTargetLocked(oldWallpaper,
6870 oldTouchedWindow.targetFlags |
6871 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006872 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6873 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006874 }
6875
6876 if (newWallpaper != nullptr) {
6877 state.addOrUpdateWindow(newWallpaper,
6878 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6879 InputTarget::Flags::WINDOW_IS_OBSCURED |
6880 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006881 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006882 }
6883}
6884
6885void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6886 ftl::Flags<InputTarget::Flags> newTargetFlags,
6887 const sp<WindowInfoHandle> fromWindowHandle,
6888 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006889 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006890 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006891 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6892 fromWindowHandle->getInfo()->inputConfig.test(
6893 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6894 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6895 toWindowHandle->getInfo()->inputConfig.test(
6896 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6897
6898 const sp<WindowInfoHandle> oldWallpaper =
6899 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6900 const sp<WindowInfoHandle> newWallpaper =
6901 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6902 if (oldWallpaper == newWallpaper) {
6903 return;
6904 }
6905
6906 if (oldWallpaper != nullptr) {
6907 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6908 "transferring touch focus to another window");
6909 state.removeWindowByToken(oldWallpaper->getToken());
6910 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6911 }
6912
6913 if (newWallpaper != nullptr) {
6914 nsecs_t downTimeInTarget = now();
6915 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6916 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6917 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6918 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006919 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6920 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006921 std::shared_ptr<Connection> wallpaperConnection =
6922 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006923 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006924 std::shared_ptr<Connection> toConnection =
6925 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006926 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6927 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6928 wallpaperFlags);
6929 }
6930 }
6931}
6932
6933sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6934 const sp<WindowInfoHandle>& windowHandle) const {
6935 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6936 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6937 bool foundWindow = false;
6938 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6939 if (!foundWindow && otherHandle != windowHandle) {
6940 continue;
6941 }
6942 if (windowHandle == otherHandle) {
6943 foundWindow = true;
6944 continue;
6945 }
6946
6947 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6948 return otherHandle;
6949 }
6950 }
6951 return nullptr;
6952}
6953
Garfield Tane84e6f92019-08-29 17:28:41 -07006954} // namespace android::inputdispatcher