blob: f2612cf92d3d8533bbc41e4130fb29ecf28acde9 [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);
Hu Guo3cfa7382023-11-15 09:50:04 +00001329 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1330 options.displayId = keyEntry.displayId;
1331 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001333 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001335 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001336 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1337 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001338 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001339 options.displayId = motionEntry.displayId;
1340 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001341 synthesizeCancelationEventsForAllConnectionsLocked(options);
1342 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001343 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1344 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001345 options.displayId = motionEntry.displayId;
1346 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 synthesizeCancelationEventsForAllConnectionsLocked(options);
1348 }
1349 break;
1350 }
Chris Yef59a2f42020-10-16 12:55:26 -07001351 case EventEntry::Type::SENSOR: {
1352 break;
1353 }
arthurhungb89ccb02020-12-30 16:19:01 +08001354 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1355 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 break;
1357 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001358 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001359 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001360 case EventEntry::Type::CONFIGURATION_CHANGED:
1361 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001362 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001363 break;
1364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
1366}
1367
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001368static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001369 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1370 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371}
1372
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001373bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1374 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1375 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1376 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377}
1378
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001379bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001380 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
1383void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001384 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001386 if (DEBUG_APP_SWITCH) {
1387 if (handled) {
1388 ALOGD("App switch has arrived.");
1389 } else {
1390 ALOGD("App switch was abandoned.");
1391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393}
1394
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001396 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397}
1398
Prabir Pradhancef936d2021-07-21 16:17:52 +00001399bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001400 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 return false;
1402 }
1403
1404 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001405 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001406 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001407 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1408 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001409 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 return true;
1411}
1412
Prabir Pradhancef936d2021-07-21 16:17:52 +00001413void InputDispatcher::postCommandLocked(Command&& command) {
1414 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415}
1416
1417void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001418 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001420 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 releaseInboundEventLocked(entry);
1422 }
1423 traceInboundQueueLengthLocked();
1424}
1425
1426void InputDispatcher::releasePendingEventLocked() {
1427 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001429 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431}
1432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001435 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001436 if (DEBUG_DISPATCH_CYCLE) {
1437 ALOGD("Injected inbound event was dropped.");
1438 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001439 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
1441 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001442 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
1444 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445}
1446
1447void InputDispatcher::resetKeyRepeatLocked() {
1448 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001449 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 }
1451}
1452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1454 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455
Michael Wright2e732952014-09-24 13:26:59 -07001456 uint32_t policyFlags = entry->policyFlags &
1457 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001459 std::shared_ptr<KeyEntry> newEntry =
1460 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1461 entry->source, entry->displayId, policyFlags, entry->action,
1462 entry->flags, entry->keyCode, entry->scanCode,
1463 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 newEntry->syntheticRepeat = true;
1466 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001468 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469}
1470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001472 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001473 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1474 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476
1477 // Reset key repeating in case a keyboard device was added or removed or something.
1478 resetKeyRepeatLocked();
1479
1480 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001481 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1482 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001483 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001484 };
1485 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 return true;
1487}
1488
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001489bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1490 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001491 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1492 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1493 entry.deviceId);
1494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495
liushenxiang42232912021-05-21 20:24:09 +08001496 // Reset key repeating in case a keyboard device was disabled or enabled.
1497 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1498 resetKeyRepeatLocked();
1499 }
1500
Michael Wrightfb04fd52022-11-24 22:31:11 +00001501 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001502 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001504
1505 // Remove all active pointers from this device
1506 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1507 touchState.removeAllPointersForDevice(entry.deviceId);
1508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 return true;
1510}
1511
Vishnu Nairad321cd2020-08-20 16:40:21 -07001512void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001513 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001514 if (mPendingEvent != nullptr) {
1515 // Move the pending event to the front of the queue. This will give the chance
1516 // for the pending event to get dispatched to the newly focused window
1517 mInboundQueue.push_front(mPendingEvent);
1518 mPendingEvent = nullptr;
1519 }
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 std::unique_ptr<FocusEntry> focusEntry =
1522 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1523 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001524
1525 // This event should go to the front of the queue, but behind all other focus events
1526 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001528 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001529 [](const std::shared_ptr<EventEntry>& event) {
1530 return event->type == EventEntry::Type::FOCUS;
1531 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001532
1533 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001534 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001535}
1536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001538 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001539 if (channel == nullptr) {
1540 return; // Window has gone away
1541 }
1542 InputTarget target;
1543 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001544 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001545 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001546 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1547 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001548 std::string reason = std::string("reason=").append(entry->reason);
1549 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001550 dispatchEventLocked(currentTime, entry, {target});
1551}
1552
Prabir Pradhan99987712020-11-10 18:43:05 -08001553void InputDispatcher::dispatchPointerCaptureChangedLocked(
1554 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1555 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001556 dropReason = DropReason::NOT_DROPPED;
1557
Prabir Pradhan99987712020-11-10 18:43:05 -08001558 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001559 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001560
1561 if (entry->pointerCaptureRequest.enable) {
1562 // Enable Pointer Capture.
1563 if (haveWindowWithPointerCapture &&
1564 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001565 // This can happen if pointer capture is disabled and re-enabled before we notify the
1566 // app of the state change, so there is no need to notify the app.
1567 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1568 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001569 }
1570 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001571 // This can happen if a window requests capture and immediately releases capture.
1572 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001573 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001574 return;
1575 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001576 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1577 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1578 return;
1579 }
1580
Vishnu Nairc519ff72021-01-21 08:23:08 -08001581 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001582 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1583 mWindowTokenWithPointerCapture = token;
1584 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001585 // Disable Pointer Capture.
1586 // We do not check if the sequence number matches for requests to disable Pointer Capture
1587 // for two reasons:
1588 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1589 // to disable capture with the same sequence number: one generated by
1590 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1591 // Capture being disabled in InputReader.
1592 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1593 // actual Pointer Capture state that affects events being generated by input devices is
1594 // in InputReader.
1595 if (!haveWindowWithPointerCapture) {
1596 // Pointer capture was already forcefully disabled because of focus change.
1597 dropReason = DropReason::NOT_DROPPED;
1598 return;
1599 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001600 token = mWindowTokenWithPointerCapture;
1601 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001602 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001603 setPointerCaptureLocked(false);
1604 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001605 }
1606
1607 auto channel = getInputChannelLocked(token);
1608 if (channel == nullptr) {
1609 // Window has gone away, clean up Pointer Capture state.
1610 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001611 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001612 setPointerCaptureLocked(false);
1613 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001614 return;
1615 }
1616 InputTarget target;
1617 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001618 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001619 entry->dispatchInProgress = true;
1620 dispatchEventLocked(currentTime, entry, {target});
1621
1622 dropReason = DropReason::NOT_DROPPED;
1623}
1624
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001625void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1626 const std::shared_ptr<TouchModeEntry>& entry) {
1627 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001628 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001629 if (windowHandles.empty()) {
1630 return;
1631 }
1632 const std::vector<InputTarget> inputTargets =
1633 getInputTargetsFromWindowHandlesLocked(windowHandles);
1634 if (inputTargets.empty()) {
1635 return;
1636 }
1637 entry->dispatchInProgress = true;
1638 dispatchEventLocked(currentTime, entry, inputTargets);
1639}
1640
1641std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1642 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1643 std::vector<InputTarget> inputTargets;
1644 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001645 const sp<IBinder>& token = handle->getToken();
1646 if (token == nullptr) {
1647 continue;
1648 }
1649 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1650 if (channel == nullptr) {
1651 continue; // Window has gone away
1652 }
1653 InputTarget target;
1654 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001655 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001656 inputTargets.push_back(target);
1657 }
1658 return inputTargets;
1659}
1660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 if (!entry->dispatchInProgress) {
1665 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1666 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1667 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1668 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001669 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 // We have seen two identical key downs in a row which indicates that the device
1671 // driver is automatically generating key repeats itself. We take note of the
1672 // repeat here, but we disable our own next key repeat timer since it is clear that
1673 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001674 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1675 // Make sure we don't get key down from a different device. If a different
1676 // device Id has same key pressed down, the new device Id will replace the
1677 // current one to hold the key repeat with repeat count reset.
1678 // In the future when got a KEY_UP on the device id, drop it and do not
1679 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1681 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001682 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 } else {
1684 // Not a repeat. Save key down state in case we do see a repeat later.
1685 resetKeyRepeatLocked();
1686 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1687 }
1688 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001689 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1690 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001691 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001692 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001693 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1694 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001695 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 resetKeyRepeatLocked();
1697 }
1698
1699 if (entry->repeatCount == 1) {
1700 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1701 } else {
1702 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1703 }
1704
1705 entry->dispatchInProgress = true;
1706
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001707 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 }
1709
1710 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001711 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 if (currentTime < entry->interceptKeyWakeupTime) {
1713 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1714 *nextWakeupTime = entry->interceptKeyWakeupTime;
1715 }
1716 return false; // wait until next wakeup
1717 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001718 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 entry->interceptKeyWakeupTime = 0;
1720 }
1721
1722 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001723 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001725 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001726 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001727
1728 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1729 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1730 };
1731 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001732 // Poke user activity for keys not passed to user
1733 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 return false; // wait for the command to run
1735 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001736 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001738 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001739 if (*dropReason == DropReason::NOT_DROPPED) {
1740 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 }
1742 }
1743
1744 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001745 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001746 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001747 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1748 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001749 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001750 // Poke user activity for undispatched keys
1751 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 return true;
1753 }
1754
1755 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001756 InputEventInjectionResult injectionResult;
1757 sp<WindowInfoHandle> focusedWindow =
1758 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1759 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001760 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 return false;
1762 }
1763
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001764 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001765 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 return true;
1767 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001768 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1769
1770 std::vector<InputTarget> inputTargets;
1771 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001772 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001773 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001775 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001776 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777
1778 // Dispatch the key.
1779 dispatchEventLocked(currentTime, entry, inputTargets);
1780 return true;
1781}
1782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001783void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001784 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1785 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1786 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1787 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1788 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1789 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1790 entry.metaState, entry.repeatCount, entry.downTime);
1791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792}
1793
Prabir Pradhancef936d2021-07-21 16:17:52 +00001794void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1795 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001796 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001797 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1798 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1799 "source=0x%x, sensorType=%s",
1800 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001801 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001802 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001803 auto command = [this, entry]() REQUIRES(mLock) {
1804 scoped_unlock unlock(mLock);
1805
1806 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001807 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001808 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001809 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1810 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001811 };
1812 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001813}
1814
1815bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001816 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1817 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001818 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001819 }
Chris Yef59a2f42020-10-16 12:55:26 -07001820 { // acquire lock
1821 std::scoped_lock _l(mLock);
1822
1823 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1824 std::shared_ptr<EventEntry> entry = *it;
1825 if (entry->type == EventEntry::Type::SENSOR) {
1826 it = mInboundQueue.erase(it);
1827 releaseInboundEventLocked(entry);
1828 }
1829 }
1830 }
1831 return true;
1832}
1833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001834bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001835 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001836 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 entry->dispatchInProgress = true;
1840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 }
1843
1844 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001845 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001846 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1848 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 return true;
1850 }
1851
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001852 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
1854 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001855 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
1857 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 if (isPointerEvent) {
1860 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001861
1862 if (mDragState &&
1863 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1864 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1865 pilferPointersLocked(mDragState->dragWindow->getToken());
1866 }
1867
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001868 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001869 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001870 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001871 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1872 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 } else {
1874 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001875 sp<WindowInfoHandle> focusedWindow =
1876 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1877 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1878 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1879 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001880 InputTarget::Flags::FOREGROUND |
1881 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001882 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001885 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 return false;
1887 }
1888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001889 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001890 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001891 return true;
1892 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001894 CancelationOptions::Mode mode(
1895 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1896 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001897 CancelationOptions options(mode, "input event injection failed");
1898 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 return true;
1900 }
1901
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001902 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001903 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 // Dispatch the motion.
1906 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001907 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001908 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 synthesizeCancelationEventsForAllConnectionsLocked(options);
1910 }
1911 dispatchEventLocked(currentTime, entry, inputTargets);
1912 return true;
1913}
1914
chaviw98318de2021-05-19 16:45:23 -05001915void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001916 bool isExiting, const int32_t rawX,
1917 const int32_t rawY) {
1918 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001919 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001920 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1921 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001922
1923 enqueueInboundEventLocked(std::move(dragEntry));
1924}
1925
1926void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1927 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1928 if (channel == nullptr) {
1929 return; // Window has gone away
1930 }
1931 InputTarget target;
1932 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001933 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001934 entry->dispatchInProgress = true;
1935 dispatchEventLocked(currentTime, entry, {target});
1936}
1937
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001938void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001939 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001940 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001941 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001942 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001943 "metaState=0x%x, buttonState=0x%x,"
1944 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001945 prefix, entry.eventTime, entry.deviceId,
1946 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1947 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1948 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1949 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001951 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001952 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001953 "x=%f, y=%f, pressure=%f, size=%f, "
1954 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1955 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001956 i, entry.pointerProperties[i].id,
1957 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001958 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1959 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1960 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1961 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1962 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1963 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1964 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1965 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1966 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969}
1970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001971void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1972 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001973 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001974 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001975 if (DEBUG_DISPATCH_CYCLE) {
1976 ALOGD("dispatchEventToCurrentInputTargets");
1977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001979 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001980
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1982
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001983 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001985 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001986 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001987 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001988 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001989 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001991 if (DEBUG_FOCUS) {
1992 ALOGD("Dropping event delivery to target with channel '%s' because it "
1993 "is no longer registered with the input dispatcher.",
1994 inputTarget.inputChannel->getName().c_str());
1995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 }
1997 }
1998}
1999
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002000void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2002 // If the policy decides to close the app, we will get a channel removal event via
2003 // unregisterInputChannel, and will clean up the connection that way. We are already not
2004 // sending new pointers to the connection when it blocked, but focused events will continue to
2005 // pile up.
2006 ALOGW("Canceling events for %s because it is unresponsive",
2007 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002008 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002009 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002010 "application not responding");
2011 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 }
2013}
2014
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002015void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002016 if (DEBUG_FOCUS) {
2017 ALOGD("Resetting ANR timeouts.");
2018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019
2020 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002022 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023}
2024
Tiger Huang721e26f2018-07-24 22:26:19 +08002025/**
2026 * Get the display id that the given event should go to. If this event specifies a valid display id,
2027 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2028 * Focused display is the display that the user most recently interacted with.
2029 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002030int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002031 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002033 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2035 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 break;
2037 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002038 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002039 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2040 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 break;
2042 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002043 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002044 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002045 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002046 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002047 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002048 case EventEntry::Type::SENSOR:
2049 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002050 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002051 return ADISPLAY_ID_NONE;
2052 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002053 }
2054 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2055}
2056
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002057bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2058 const char* focusedWindowName) {
2059 if (mAnrTracker.empty()) {
2060 // already processed all events that we waited for
2061 mKeyIsWaitingForEventsTimeout = std::nullopt;
2062 return false;
2063 }
2064
2065 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2066 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002067 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002068 mKeyIsWaitingForEventsTimeout = currentTime +
2069 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2070 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 return true;
2072 }
2073
2074 // We still have pending events, and already started the timer
2075 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2076 return true; // Still waiting
2077 }
2078
2079 // Waited too long, and some connection still hasn't processed all motions
2080 // Just send the key to the focused window
2081 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2082 focusedWindowName);
2083 mKeyIsWaitingForEventsTimeout = std::nullopt;
2084 return false;
2085}
2086
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002087sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2088 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2089 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002090 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091
Tiger Huang721e26f2018-07-24 22:26:19 +08002092 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002093 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002094 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002095 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2096
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 // If there is no currently focused window and no focused application
2098 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002099 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2100 ALOGI("Dropping %s event because there is no focused window or focused application in "
2101 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002102 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002103 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
2105
Vishnu Nair062a8672021-09-03 16:07:44 -07002106 // Drop key events if requested by input feature
2107 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002108 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002109 }
2110
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2112 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2113 // start interacting with another application via touch (app switch). This code can be removed
2114 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2115 // an app is expected to have a focused window.
2116 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2117 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2118 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002119 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2120 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2121 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002122 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002123 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002124 ALOGW("Waiting because no window has focus but %s may eventually add a "
2125 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002126 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002127 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002128 outInjectionResult = InputEventInjectionResult::PENDING;
2129 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002130 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2131 // Already raised ANR. Drop the event
2132 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002133 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002134 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002135 } else {
2136 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002137 outInjectionResult = InputEventInjectionResult::PENDING;
2138 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 }
2140 }
2141
2142 // we have a valid, non-null focused window
2143 resetNoFocusedWindowTimeoutLocked();
2144
Prabir Pradhan5735a322022-04-11 17:23:34 +00002145 // Verify targeted injection.
2146 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2147 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002148 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2149 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
2151
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002152 if (focusedWindowHandle->getInfo()->inputConfig.test(
2153 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002154 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002155 outInjectionResult = InputEventInjectionResult::PENDING;
2156 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002157 }
2158
2159 // If the event is a key event, then we must wait for all previous events to
2160 // complete before delivering it because previous events may have the
2161 // side-effect of transferring focus to a different window and we want to
2162 // ensure that the following keys are sent to the new window.
2163 //
2164 // Suppose the user touches a button in a window then immediately presses "A".
2165 // If the button causes a pop-up window to appear then we want to ensure that
2166 // the "A" key is delivered to the new pop-up window. This is because users
2167 // often anticipate pending UI changes when typing on a keyboard.
2168 // To obtain this behavior, we must serialize key events with respect to all
2169 // prior input events.
2170 if (entry.type == EventEntry::Type::KEY) {
2171 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2172 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002173 outInjectionResult = InputEventInjectionResult::PENDING;
2174 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
2177
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002178 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2179 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180}
2181
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182/**
2183 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2184 * that are currently unresponsive.
2185 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002186std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2187 const std::vector<Monitor>& monitors) const {
2188 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002189 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002190 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002191 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002192 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002193 if (connection == nullptr) {
2194 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002195 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002196 return false;
2197 }
2198 if (!connection->responsive) {
2199 ALOGW("Unresponsive monitor %s will not get the new gesture",
2200 connection->inputChannel->getName().c_str());
2201 return false;
2202 }
2203 return true;
2204 });
2205 return responsiveMonitors;
2206}
2207
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002208/**
2209 * In general, touch should be always split between windows. Some exceptions:
2210 * 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 -07002211 * from the same device, *and* the window that's receiving the current pointer does not support
2212 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002213 * 2. Don't split mouse events
2214 */
2215bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2216 const MotionEntry& entry) const {
2217 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2218 // We should never split mouse events
2219 return false;
2220 }
2221 for (const TouchedWindow& touchedWindow : touchState.windows) {
2222 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2223 // Spy windows should not affect whether or not touch is split.
2224 continue;
2225 }
2226 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2227 continue;
2228 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002229 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2230 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2231 // Wallpaper window should not affect whether or not touch is split
2232 continue;
2233 }
2234
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002235 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002236 return false;
2237 }
2238 }
2239 return true;
2240}
2241
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002242std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002243 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2244 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002245 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002247 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 // For security reasons, we defer updating the touch state until we are sure that
2249 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002250 const int32_t displayId = entry.displayId;
2251 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002252 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253
2254 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002255 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002257 // Copy current touch state into tempTouchState.
2258 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2259 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002260 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002261 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002262 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2263 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002264 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002265 }
2266
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002267 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002268 bool switchedDevice = false;
2269 if (oldState != nullptr) {
2270 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2271 const bool anotherDeviceIsActive =
2272 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2273 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002274 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002275
2276 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2277 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2278 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002279 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2280 // touchable windows.
2281 const bool wasDown = oldState != nullptr && oldState->isDown();
2282 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2283 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002284 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2285 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2286 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002287 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002288
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002289 // If pointers are already down, let's finish the current gesture and ignore the new events
2290 // from another device. However, if the new event is a down event, let's cancel the current
2291 // touch and let the new one take over.
2292 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002293 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002294 << " is already down in display " << displayId << ": " << entry.getDescription();
2295 // TODO(b/211379801): test multiple simultaneous input streams.
2296 outInjectionResult = InputEventInjectionResult::FAILED;
2297 return {}; // wrong device
2298 }
2299
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002301 // If a new gesture is starting, clear the touch state completely.
2302 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002304 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002305 ALOGI("Dropping move event because a pointer for a different device is already active "
2306 "in display %" PRId32,
2307 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002308 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002309 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002310 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
2312
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002313 if (isHoverAction) {
2314 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2315 // all of the existing hovering pointers and recompute.
2316 tempTouchState.clearHoveringPointers();
2317 }
2318
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2320 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002321 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002323 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2324 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002325 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002326 auto [newTouchedWindowHandle, outsideTargets] =
2327 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002328
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002329 if (isDown) {
2330 targets += outsideTargets;
2331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002333 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002334 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002337 }
2338
Prabir Pradhan5735a322022-04-11 17:23:34 +00002339 // Verify targeted injection.
2340 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2341 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002342 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002343 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002344 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002345 }
2346
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002347 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002348 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002349 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2350 // New window supports splitting, but we should never split mouse events.
2351 isSplit = !isFromMouse;
2352 } else if (isSplit) {
2353 // New window does not support splitting but we have already split events.
2354 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002355 newTouchedWindowHandle = nullptr;
2356 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002357 } else {
2358 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002359 // be delivered to a new window which supports split touch. Pointers from a mouse device
2360 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002361 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002362 }
2363
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002364 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002365 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002367 // Process the foreground window first so that it is the first to receive the event.
2368 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002369 }
2370
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002371 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002372 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2373 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002374 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002375 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002376 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377 }
2378
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002380 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002381 continue;
2382 }
2383
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002384 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2385 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002386 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002387 // The "windowHandle" is the target of this hovering pointer.
2388 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002389 }
2390
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002392 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002394 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2395 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002396 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002397 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398
2399 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002400 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 }
2402 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002403 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002404 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002405 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002406 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002407
2408 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002409 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002410 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002411 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002412 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002414 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2415 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2416
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002417 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2418 // still add a window to the touch state. We should avoid doing that, but some of the
2419 // later checks ("at least one foreground window") rely on this in order to dispatch
2420 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002421 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002422 isDownOrPointerDown
2423 ? std::make_optional(entry.eventTime)
2424 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002425
2426 // If this is the pointer going down and the touched window has a wallpaper
2427 // then also add the touched wallpaper windows so they are locked in for the duration
2428 // of the touch gesture.
2429 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2430 // engine only supports touch events. We would need to add a mechanism similar
2431 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002432 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002433 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2434 windowHandle->getInfo()->inputConfig.test(
2435 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2436 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2437 if (wallpaper != nullptr) {
2438 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2439 InputTarget::Flags::WINDOW_IS_OBSCURED |
2440 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2441 InputTarget::Flags::DISPATCH_AS_IS;
2442 if (isSplit) {
2443 wallpaperFlags |= InputTarget::Flags::SPLIT;
2444 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002445 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2446 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002447 }
2448 }
2449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002451
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002452 // If a window is already pilfering some pointers, give it this new pointer as well and
2453 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2454 // which is a specific behaviour that we want.
2455 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2456 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002457 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2458 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002459 // This window is already pilfering some pointers, and this new pointer is also
2460 // going to it. Therefore, take over this pointer and don't give it to anyone
2461 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002462 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002463 }
2464 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002465
2466 // Restrict all pilfered pointers to the pilfering windows.
2467 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 } else {
2469 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2470
2471 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002472 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002473 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2474 "dropped the pointer down event in display "
2475 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002476 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002477 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
2479
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002480 // If the pointer is not currently hovering, then ignore the event.
2481 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2482 const int32_t pointerId = entry.pointerProperties[0].id;
2483 if (oldState == nullptr ||
2484 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2485 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2486 "display "
2487 << displayId << ": " << entry.getDescription();
2488 outInjectionResult = InputEventInjectionResult::FAILED;
2489 return {};
2490 }
2491 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2492 }
2493
arthurhung6d4bed92021-03-17 11:59:33 +08002494 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002495
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002497 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002498 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002499 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002500 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002501 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002502 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002503 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002504 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002505
Prabir Pradhan5735a322022-04-11 17:23:34 +00002506 // Verify targeted injection.
2507 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2508 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002509 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002510 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002511 }
2512
Vishnu Nair062a8672021-09-03 16:07:44 -07002513 // Drop touch events if requested by input feature
2514 if (newTouchedWindowHandle != nullptr &&
2515 shouldDropInput(entry, newTouchedWindowHandle)) {
2516 newTouchedWindowHandle = nullptr;
2517 }
2518
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002519 if (newTouchedWindowHandle != nullptr &&
2520 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002521 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2522 oldTouchedWindowHandle->getName().c_str(),
2523 newTouchedWindowHandle->getName().c_str(), displayId);
2524
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002526 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002527 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002528 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002529
2530 const TouchedWindow& touchedWindow =
2531 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2532 addWindowTargetLocked(oldTouchedWindowHandle,
2533 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002534 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535
2536 // Make a slippery entrance into the new window.
2537 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002538 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002541 ftl::Flags<InputTarget::Flags> targetFlags =
2542 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002543 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002544 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002547 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002550 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002551 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002552 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 }
2554
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002555 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2556 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002557
2558 // Check if the wallpaper window should deliver the corresponding event.
2559 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002560 tempTouchState, entry.deviceId, pointerId, targets);
2561 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2562 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564 }
Arthur Hung96483742022-11-15 03:30:48 +00002565
2566 // Update the pointerIds for non-splittable when it received pointer down.
2567 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2568 // If no split, we suppose all touched windows should receive pointer down.
2569 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2570 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2571 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2572 // Ignore drag window for it should just track one pointer.
2573 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2574 continue;
2575 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002576 touchedWindow.addTouchingPointer(entry.deviceId,
2577 entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002578 }
2579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002582 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002583 {
2584 std::vector<TouchedWindow> hoveringWindows =
2585 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2586 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002587 std::optional<InputTarget> target =
2588 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002589 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002590 if (!target) {
2591 continue;
2592 }
2593 // Hardcode to single hovering pointer for now.
2594 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2595 pointerIds.set(entry.pointerProperties[0].id);
2596 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2597 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600
Prabir Pradhan5735a322022-04-11 17:23:34 +00002601 // Ensure that all touched windows are valid for injection.
2602 if (entry.injectionState != nullptr) {
2603 std::string errs;
2604 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002605 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2606 if (err) errs += "\n - " + *err;
2607 }
2608 if (!errs.empty()) {
2609 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002610 "%s:%s",
2611 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002612 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002613 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002614 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002615 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002616
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002617 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2618 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002620 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002621 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002622 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002623 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002624 for (InputTarget& target : targets) {
2625 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2626 sp<WindowInfoHandle> targetWindow =
2627 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2628 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2629 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 }
2632 }
2633 }
2634 }
2635
Harry Cuttsb166c002023-05-09 13:06:05 +00002636 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2637 // only want the system UI to handle these gestures.
2638 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2639 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2640 if (isTouchpadNavGesture) {
2641 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2642 }
2643
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002644 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002645 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002646 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2647 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002648 // Windows with hovering pointers are getting persisted inside TouchState.
2649 // Do not send this event to those windows.
2650 continue;
2651 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002652
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002653 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002654 touchedWindow.getTouchingPointers(entry.deviceId),
2655 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002656 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002657
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002658 // During targeted injection, only allow owned targets to receive events
2659 std::erase_if(targets, [&](const InputTarget& target) {
2660 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2661 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2662 if (err) {
2663 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2664 << ": " << (*err);
2665 return true;
2666 }
2667 return false;
2668 });
2669
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002670 if (targets.empty()) {
2671 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2672 outInjectionResult = InputEventInjectionResult::FAILED;
2673 return {};
2674 }
2675
2676 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2677 // window that is actually receiving the entire gesture.
2678 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2679 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2680 })) {
2681 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2682 << entry.getDescription();
2683 outInjectionResult = InputEventInjectionResult::FAILED;
2684 return {};
2685 }
2686
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002687 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002688 // Drop the outside or hover touch windows since we will not care about them
2689 // in the next iteration.
2690 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002693 if (switchedDevice) {
2694 if (DEBUG_FOCUS) {
2695 ALOGD("Conflicting pointer actions: Switched to a different device.");
2696 }
2697 *outConflictingPointerActions = true;
2698 }
2699
2700 if (isHoverAction) {
2701 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002702 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002703 ALOGD_IF(DEBUG_FOCUS,
2704 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002705 *outConflictingPointerActions = true;
2706 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002707 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2708 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002709 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002710 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2711 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002712 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002713 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 // All pointers up or canceled.
2715 tempTouchState.reset();
2716 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2717 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002718 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2719 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002720 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002721 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2723 // One pointer went up.
2724 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2725 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002727 for (size_t i = 0; i < tempTouchState.windows.size();) {
2728 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002729 touchedWindow.removeTouchingPointer(entry.deviceId, pointerId);
2730 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2732 continue;
2733 }
2734 i += 1;
2735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002738 // Save changes unless the action was scroll in which case the temporary touch
2739 // state was only valid for this one action.
2740 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002741 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002742 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002743 mTouchStatesByDisplay[displayId] = tempTouchState;
2744 } else {
2745 mTouchStatesByDisplay.erase(displayId);
2746 }
2747 }
2748
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002749 if (tempTouchState.windows.empty()) {
2750 mTouchStatesByDisplay.erase(displayId);
2751 }
2752
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002753 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754}
2755
arthurhung6d4bed92021-03-17 11:59:33 +08002756void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002757 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2758 // have an explicit reason to support it.
2759 constexpr bool isStylus = false;
2760
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002761 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002762 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002763 if (dropWindow) {
2764 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002765 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002766 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002767 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002768 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002769 }
2770 mDragState.reset();
2771}
2772
2773void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002774 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002775 return;
2776 }
2777
arthurhung6d4bed92021-03-17 11:59:33 +08002778 if (!mDragState->isStartDrag) {
2779 mDragState->isStartDrag = true;
2780 mDragState->isStylusButtonDownAtStart =
2781 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2782 }
2783
Arthur Hung54745652022-04-20 07:17:41 +00002784 // Find the pointer index by id.
2785 int32_t pointerIndex = 0;
2786 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2787 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2788 if (pointerProperties.id == mDragState->pointerId) {
2789 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002790 }
Arthur Hung54745652022-04-20 07:17:41 +00002791 }
arthurhung6d4bed92021-03-17 11:59:33 +08002792
Arthur Hung54745652022-04-20 07:17:41 +00002793 if (uint32_t(pointerIndex) == entry.pointerCount) {
2794 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002795 }
2796
2797 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2798 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2799 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2800
2801 switch (maskedAction) {
2802 case AMOTION_EVENT_ACTION_MOVE: {
2803 // Handle the special case : stylus button no longer pressed.
2804 bool isStylusButtonDown =
2805 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2806 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2807 finishDragAndDrop(entry.displayId, x, y);
2808 return;
2809 }
2810
2811 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2812 // until we have an explicit reason to support it.
2813 constexpr bool isStylus = false;
2814
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002815 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002816 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002817 // enqueue drag exit if needed.
2818 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2819 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2820 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002821 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002822 y);
2823 }
2824 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2825 }
2826 // enqueue drag location if needed.
2827 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002828 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002829 }
2830 break;
2831 }
2832
2833 case AMOTION_EVENT_ACTION_POINTER_UP:
2834 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2835 break;
2836 }
2837 // The drag pointer is up.
2838 [[fallthrough]];
2839 case AMOTION_EVENT_ACTION_UP:
2840 finishDragAndDrop(entry.displayId, x, y);
2841 break;
2842 case AMOTION_EVENT_ACTION_CANCEL: {
2843 ALOGD("Receiving cancel when drag and drop.");
2844 sendDropWindowCommandLocked(nullptr, 0, 0);
2845 mDragState.reset();
2846 break;
2847 }
arthurhungb89ccb02020-12-30 16:19:01 +08002848 }
2849}
2850
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002851std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2852 const sp<android::gui::WindowInfoHandle>& windowHandle,
2853 ftl::Flags<InputTarget::Flags> targetFlags,
2854 std::optional<nsecs_t> firstDownTimeInTarget) const {
2855 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2856 if (inputChannel == nullptr) {
2857 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2858 return {};
2859 }
2860 InputTarget inputTarget;
2861 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002862 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002863 inputTarget.flags = targetFlags;
2864 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2865 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2866 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2867 if (displayInfoIt != mDisplayInfos.end()) {
2868 inputTarget.displayTransform = displayInfoIt->second.transform;
2869 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002870 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002871 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2872 }
2873 return inputTarget;
2874}
2875
chaviw98318de2021-05-19 16:45:23 -05002876void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002877 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002878 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002879 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002880 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002881 std::vector<InputTarget>::iterator it =
2882 std::find_if(inputTargets.begin(), inputTargets.end(),
2883 [&windowHandle](const InputTarget& inputTarget) {
2884 return inputTarget.inputChannel->getConnectionToken() ==
2885 windowHandle->getToken();
2886 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002887
chaviw98318de2021-05-19 16:45:23 -05002888 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002889
2890 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002891 std::optional<InputTarget> target =
2892 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2893 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002894 return;
2895 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002896 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002897 it = inputTargets.end() - 1;
2898 }
2899
2900 ALOG_ASSERT(it->flags == targetFlags);
2901 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2902
chaviw1ff3d1e2020-07-01 15:53:47 -07002903 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904}
2905
Michael Wright3dd60e22019-03-27 22:06:44 +00002906void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002907 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002908 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2909 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002910
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002911 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2912 InputTarget target;
2913 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002914 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002915 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2916 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002917 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2918 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002919 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002920 target.setDefaultPointerTransform(target.displayTransform);
2921 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 }
2923}
2924
Robert Carrc9bf1d32020-04-13 17:21:08 -07002925/**
2926 * Indicate whether one window handle should be considered as obscuring
2927 * another window handle. We only check a few preconditions. Actually
2928 * checking the bounds is left to the caller.
2929 */
chaviw98318de2021-05-19 16:45:23 -05002930static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2931 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932 // Compare by token so cloned layers aren't counted
2933 if (haveSameToken(windowHandle, otherHandle)) {
2934 return false;
2935 }
2936 auto info = windowHandle->getInfo();
2937 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002938 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002939 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002940 } else if (otherInfo->alpha == 0 &&
2941 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002942 // Those act as if they were invisible, so we don't need to flag them.
2943 // We do want to potentially flag touchable windows even if they have 0
2944 // opacity, since they can consume touches and alter the effects of the
2945 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002946 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002947 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2948 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002949 } else if (info->ownerUid == otherInfo->ownerUid) {
2950 // If ownerUid is the same we don't generate occlusion events as there
2951 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002952 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002953 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002954 return false;
2955 } else if (otherInfo->displayId != info->displayId) {
2956 return false;
2957 }
2958 return true;
2959}
2960
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002961/**
2962 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2963 * untrusted, one should check:
2964 *
2965 * 1. If result.hasBlockingOcclusion is true.
2966 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2967 * BLOCK_UNTRUSTED.
2968 *
2969 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2970 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2971 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2972 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2973 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2974 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2975 *
2976 * If neither of those is true, then it means the touch can be allowed.
2977 */
2978InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002979 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2980 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002981 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002982 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002983 TouchOcclusionInfo info;
2984 info.hasBlockingOcclusion = false;
2985 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002986 info.obscuringUid = gui::Uid::INVALID;
2987 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002988 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002989 if (windowHandle == otherHandle) {
2990 break; // All future windows are below us. Exit early.
2991 }
chaviw98318de2021-05-19 16:45:23 -05002992 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002993 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2994 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002995 if (DEBUG_TOUCH_OCCLUSION) {
2996 info.debugInfo.push_back(
2997 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2998 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002999 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3000 // we perform the checks below to see if the touch can be propagated or not based on the
3001 // window's touch occlusion mode
3002 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3003 info.hasBlockingOcclusion = true;
3004 info.obscuringUid = otherInfo->ownerUid;
3005 info.obscuringPackage = otherInfo->packageName;
3006 break;
3007 }
3008 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003009 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003010 float opacity =
3011 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3012 // Given windows A and B:
3013 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3014 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3015 opacityByUid[uid] = opacity;
3016 if (opacity > info.obscuringOpacity) {
3017 info.obscuringOpacity = opacity;
3018 info.obscuringUid = uid;
3019 info.obscuringPackage = otherInfo->packageName;
3020 }
3021 }
3022 }
3023 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003024 if (DEBUG_TOUCH_OCCLUSION) {
3025 info.debugInfo.push_back(
3026 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3027 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003028 return info;
3029}
3030
chaviw98318de2021-05-19 16:45:23 -05003031std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003032 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003033 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003034 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3035 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3036 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003037 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003038 info->ownerUid.toString().c_str(), info->id,
3039 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3040 info->frameTop, info->frameRight, info->frameBottom,
3041 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3042 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3043 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003044 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003045}
3046
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003047bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3048 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003049 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3050 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003051 return false;
3052 }
3053 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003054 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003055 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003056 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003057 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3058 return false;
3059 }
3060 return true;
3061}
3062
chaviw98318de2021-05-19 16:45:23 -05003063bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003066 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3067 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003068 if (windowHandle == otherHandle) {
3069 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 }
chaviw98318de2021-05-19 16:45:23 -05003071 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003072 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003073 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 return true;
3075 }
3076 }
3077 return false;
3078}
3079
chaviw98318de2021-05-19 16:45:23 -05003080bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003081 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003082 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3083 const WindowInfo* windowInfo = windowHandle->getInfo();
3084 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003085 if (windowHandle == otherHandle) {
3086 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003087 }
chaviw98318de2021-05-19 16:45:23 -05003088 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003089 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003090 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003091 return true;
3092 }
3093 }
3094 return false;
3095}
3096
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003097std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003098 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003099 if (applicationHandle != nullptr) {
3100 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003101 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102 } else {
3103 return applicationHandle->getName();
3104 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003105 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003106 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003108 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 }
3110}
3111
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003112void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003113 if (!isUserActivityEvent(eventEntry)) {
3114 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003115 return;
3116 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003117 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003118 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003119 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003120 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003121 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003122 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003123 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
3125 }
3126
3127 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003128 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003129 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003130 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3131 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 return;
3133 }
Josep del Riob3981622023-04-18 15:49:45 +00003134 if (windowDisablingUserActivityInfo != nullptr) {
3135 if (DEBUG_DISPATCH_CYCLE) {
3136 ALOGD("Not poking user activity: disabled by window '%s'.",
3137 windowDisablingUserActivityInfo->name.c_str());
3138 }
3139 return;
3140 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003141 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 eventType = USER_ACTIVITY_EVENT_TOUCH;
3143 }
3144 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3148 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 return;
3150 }
Josep del Riob3981622023-04-18 15:49:45 +00003151 // If the key code is unknown, we don't consider it user activity
3152 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3153 return;
3154 }
3155 // Don't inhibit events that were intercepted or are not passed to
3156 // the apps, like system shortcuts
3157 if (windowDisablingUserActivityInfo != nullptr &&
3158 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3159 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3160 if (DEBUG_DISPATCH_CYCLE) {
3161 ALOGD("Not poking user activity: disabled by window '%s'.",
3162 windowDisablingUserActivityInfo->name.c_str());
3163 }
3164 return;
3165 }
3166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 eventType = USER_ACTIVITY_EVENT_BUTTON;
3168 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003170 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003171 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003172 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003173 break;
3174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
3176
Prabir Pradhancef936d2021-07-21 16:17:52 +00003177 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3178 REQUIRES(mLock) {
3179 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003180 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003181 };
3182 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183}
3184
3185void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003186 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003187 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003188 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003189 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003191 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003192 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003193 ATRACE_NAME(message.c_str());
3194 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003195 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003196 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003197 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003198 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003199 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 inputTarget.getPointerInfoString().c_str());
3201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
3203 // Skip this event if the connection status is not normal.
3204 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003205 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003206 if (DEBUG_DISPATCH_CYCLE) {
3207 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003208 connection->getInputChannelName().c_str(),
3209 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 return;
3212 }
3213
3214 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003215 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003216 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003217 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003218 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003220 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003221 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003222 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3223 logDispatchStateLocked();
3224 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3225 "target on connection "
3226 << connection->getInputChannelName() << " for "
3227 << originalMotionEntry.getDescription();
3228 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003229 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003230 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3231 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 if (!splitMotionEntry) {
3233 return; // split event was dropped
3234 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003235 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3236 std::string reason = std::string("reason=pointer cancel on split window");
3237 android_log_event_list(LOGTAG_INPUT_CANCEL)
3238 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3239 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003240 if (DEBUG_FOCUS) {
3241 ALOGD("channel '%s' ~ Split motion event.",
3242 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003243 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003244 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003245 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3246 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 return;
3248 }
3249 }
3250
3251 // Not splitting. Enqueue dispatch entries for the event as is.
3252 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3253}
3254
3255void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003256 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003258 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003259 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003260 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003261 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003262 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003263 ATRACE_NAME(message.c_str());
3264 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003265 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3266 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003267
hongzuo liu95785e22022-09-06 02:51:35 +00003268 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
3270 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
3284 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003285 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 startDispatchCycleLocked(currentTime, connection);
3287 }
3288}
3289
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003290void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003292 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003294 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3296 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003298 ATRACE_NAME(message.c_str());
3299 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003300 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3301 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 return;
3303 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003304
3305 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3306 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
3308 // This is a new event.
3309 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003310 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003311 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003313 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3314 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003317 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003318 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003320 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003321 dispatchEntry->resolvedAction = keyEntry.action;
3322 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3325 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003326 LOG(WARNING) << "channel " << connection->getInputChannelName()
3327 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 return; // skip the inconsistent event
3329 }
3330 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003333 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003335 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3336 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3337 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3338 static_cast<int32_t>(IdGenerator::Source::OTHER);
3339 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003342 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003344 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003345 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003346 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003348 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3350 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003351 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003352 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 }
3354 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003355 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3356 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003357 if (DEBUG_DISPATCH_CYCLE) {
3358 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3359 "enter event",
3360 connection->getInputChannelName().c_str());
3361 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003362 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3363 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003367 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003368 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3369 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3370 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003371 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3373 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003374 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003375 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3379 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003380 LOG(WARNING) << "channel " << connection->getInputChannelName()
3381 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 return; // skip the inconsistent event
3383 }
3384
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003385 dispatchEntry->resolvedEventId =
3386 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3387 ? mIdGenerator.nextId()
3388 : motionEntry.id;
3389 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3390 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3391 ") to MotionEvent(id=0x%" PRIx32 ").",
3392 motionEntry.id, dispatchEntry->resolvedEventId);
3393 ATRACE_NAME(message.c_str());
3394 }
3395
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003396 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3397 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3398 // Skip reporting pointer down outside focus to the policy.
3399 break;
3400 }
3401
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003402 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003403 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404
3405 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003407 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003408 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003409 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3410 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003411 break;
3412 }
Chris Yef59a2f42020-10-16 12:55:26 -07003413 case EventEntry::Type::SENSOR: {
3414 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3415 break;
3416 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003417 case EventEntry::Type::CONFIGURATION_CHANGED:
3418 case EventEntry::Type::DEVICE_RESET: {
3419 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003420 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003421 break;
3422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424
3425 // Remember that we are waiting for this dispatch to complete.
3426 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003427 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
3429
3430 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003431 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003432 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003433}
3434
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003435/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003436 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003437 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003438 * The first role is to log input interaction with windows, which helps determine what the user was
3439 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3440 * that user started interacting with launcher window, as well as any other window that received
3441 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3442 * when the set of tokens that received the event changes. It is not logged again as long as the
3443 * user is interacting with the same windows.
3444 *
3445 * The second role is to track input device activity for metrics collection. For each input event,
3446 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3447 * input_interaction logs, the device interaction is reported even when the set of interaction
3448 * tokens do not change.
3449 *
3450 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3451 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003452 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003453void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3454 const std::vector<InputTarget>& targets) {
3455 int32_t deviceId;
3456 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003457 // Skip ACTION_UP events, and all events other than keys and motions
3458 if (entry.type == EventEntry::Type::KEY) {
3459 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3460 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3461 return;
3462 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003463 deviceId = keyEntry.deviceId;
3464 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003465 } else if (entry.type == EventEntry::Type::MOTION) {
3466 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3467 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003468 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3469 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003470 return;
3471 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003472 deviceId = motionEntry.deviceId;
3473 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 } else {
3475 return; // Not a key or a motion
3476 }
3477
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003478 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003479 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003480 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003481 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003482 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003483 continue; // Skip windows that receive ACTION_OUTSIDE
3484 }
3485
3486 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003487 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003488 if (connection == nullptr) {
3489 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 }
3491 newConnectionTokens.insert(std::move(token));
3492 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003493 if (target.windowHandle) {
3494 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3495 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003496 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003497
3498 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3499 REQUIRES(mLock) {
3500 scoped_unlock unlock(mLock);
3501 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3502 };
3503 postCommandLocked(std::move(command));
3504
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003505 if (newConnectionTokens == mInteractionConnectionTokens) {
3506 return; // no change
3507 }
3508 mInteractionConnectionTokens = newConnectionTokens;
3509
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003510 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003511 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003512 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003513 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003514 std::string message = "Interaction with: " + targetList;
3515 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003516 message += "<none>";
3517 }
3518 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3519}
3520
chaviwfd6d3512019-03-25 13:23:49 -07003521void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003522 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003523 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003524 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3525 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003526 return;
3527 }
3528
Vishnu Nairc519ff72021-01-21 08:23:08 -08003529 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003530 if (focusedToken == token) {
3531 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003532 return;
3533 }
3534
Prabir Pradhancef936d2021-07-21 16:17:52 +00003535 auto command = [this, token]() REQUIRES(mLock) {
3536 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003537 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003538 };
3539 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540}
3541
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003542status_t InputDispatcher::publishMotionEvent(Connection& connection,
3543 DispatchEntry& dispatchEntry) const {
3544 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3545 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3546
3547 PointerCoords scaledCoords[MAX_POINTERS];
3548 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3549
3550 // Set the X and Y offset and X and Y scale depending on the input source.
3551 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003552 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003553 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3554 if (globalScaleFactor != 1.0f) {
3555 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3556 scaledCoords[i] = motionEntry.pointerCoords[i];
3557 // Don't apply window scale here since we don't want scale to affect raw
3558 // coordinates. The scale will be sent back to the client and applied
3559 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003560 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003561 }
3562 usingCoords = scaledCoords;
3563 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003564 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003565 // We don't want the dispatch target to know the coordinates
3566 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3567 scaledCoords[i].clear();
3568 }
3569 usingCoords = scaledCoords;
3570 }
3571
3572 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3573
3574 // Publish the motion event.
3575 return connection.inputPublisher
3576 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3577 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3578 std::move(hmac), dispatchEntry.resolvedAction,
3579 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3580 motionEntry.edgeFlags, motionEntry.metaState,
3581 motionEntry.buttonState, motionEntry.classification,
3582 dispatchEntry.transform, motionEntry.xPrecision,
3583 motionEntry.yPrecision, motionEntry.xCursorPosition,
3584 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3585 motionEntry.downTime, motionEntry.eventTime,
3586 motionEntry.pointerCount, motionEntry.pointerProperties,
3587 usingCoords);
3588}
3589
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003591 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003592 if (ATRACE_ENABLED()) {
3593 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003594 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003595 ATRACE_NAME(message.c_str());
3596 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003597 if (DEBUG_DISPATCH_CYCLE) {
3598 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003601 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003602 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003604 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003605 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
3607 // Publish the event.
3608 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003609 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3610 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003611 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003612 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3613 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003614 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3615 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3616 << connection->getInputChannelName();
3617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003620 status = connection->inputPublisher
3621 .publishKeyEvent(dispatchEntry->seq,
3622 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3623 keyEntry.source, keyEntry.displayId,
3624 std::move(hmac), dispatchEntry->resolvedAction,
3625 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3626 keyEntry.scanCode, keyEntry.metaState,
3627 keyEntry.repeatCount, keyEntry.downTime,
3628 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 }
3631
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003632 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003633 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3634 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3635 << connection->getInputChannelName();
3636 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003637 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003638 break;
3639 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003640
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003641 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003642 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003643 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003644 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003645 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003646 break;
3647 }
3648
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003649 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3650 const TouchModeEntry& touchModeEntry =
3651 static_cast<const TouchModeEntry&>(eventEntry);
3652 status = connection->inputPublisher
3653 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3654 touchModeEntry.inTouchMode);
3655
3656 break;
3657 }
3658
Prabir Pradhan99987712020-11-10 18:43:05 -08003659 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3660 const auto& captureEntry =
3661 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3662 status = connection->inputPublisher
3663 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003664 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003665 break;
3666 }
3667
arthurhungb89ccb02020-12-30 16:19:01 +08003668 case EventEntry::Type::DRAG: {
3669 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3670 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3671 dragEntry.id, dragEntry.x,
3672 dragEntry.y,
3673 dragEntry.isExiting);
3674 break;
3675 }
3676
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003677 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003678 case EventEntry::Type::DEVICE_RESET:
3679 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003680 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003681 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003682 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685
3686 // Check the result.
3687 if (status) {
3688 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003689 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003691 "This is unexpected because the wait queue is empty, so the pipe "
3692 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003693 "event to it, status=%s(%d)",
3694 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3695 status);
Harry Cutts33476232023-01-30 19:57:29 +00003696 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 } else {
3698 // Pipe is full and we are waiting for the app to finish process some events
3699 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003700 if (DEBUG_DISPATCH_CYCLE) {
3701 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3702 "waiting for the application to catch up",
3703 connection->getInputChannelName().c_str());
3704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
3706 } else {
3707 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003708 "status=%s(%d)",
3709 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3710 status);
Harry Cutts33476232023-01-30 19:57:29 +00003711 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713 return;
3714 }
3715
3716 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003717 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3718 connection->outboundQueue.end(),
3719 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003720 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003721 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003722 if (connection->responsive) {
3723 mAnrTracker.insert(dispatchEntry->timeoutTime,
3724 connection->inputChannel->getConnectionToken());
3725 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003726 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 }
3728}
3729
chaviw09c8d2d2020-08-24 15:48:26 -07003730std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3731 size_t size;
3732 switch (event.type) {
3733 case VerifiedInputEvent::Type::KEY: {
3734 size = sizeof(VerifiedKeyEvent);
3735 break;
3736 }
3737 case VerifiedInputEvent::Type::MOTION: {
3738 size = sizeof(VerifiedMotionEvent);
3739 break;
3740 }
3741 }
3742 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3743 return mHmacKeyManager.sign(start, size);
3744}
3745
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003746const std::array<uint8_t, 32> InputDispatcher::getSignature(
3747 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003748 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003749 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003750 // Only sign events up and down events as the purely move events
3751 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003752 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003753 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003754
3755 VerifiedMotionEvent verifiedEvent =
3756 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3757 verifiedEvent.actionMasked = actionMasked;
3758 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3759 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003760}
3761
3762const std::array<uint8_t, 32> InputDispatcher::getSignature(
3763 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3764 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3765 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3766 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003767 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003768}
3769
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003771 const std::shared_ptr<Connection>& connection,
3772 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003773 if (DEBUG_DISPATCH_CYCLE) {
3774 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3775 connection->getInputChannelName().c_str(), seq, toString(handled));
3776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003778 if (connection->status == Connection::Status::BROKEN ||
3779 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 return;
3781 }
3782
3783 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003784 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3785 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3786 };
3787 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788}
3789
3790void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003791 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003793 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003794 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3795 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797
3798 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003799 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003800 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003801 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003802 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
3804 // The connection appears to be unrecoverably broken.
3805 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003806 if (connection->status == Connection::Status::NORMAL) {
3807 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
3809 if (notify) {
3810 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003811 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3812 connection->getInputChannelName().c_str());
3813
3814 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003815 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003816 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003817 };
3818 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820 }
3821}
3822
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003823void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3824 while (!queue.empty()) {
3825 DispatchEntry* dispatchEntry = queue.front();
3826 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003827 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829}
3830
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003831void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003833 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 delete dispatchEntry;
3836}
3837
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003838int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3839 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003840 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003841 if (connection == nullptr) {
3842 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3843 connectionToken.get(), events);
3844 return 0; // remove the callback
3845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003847 bool notify;
3848 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3849 if (!(events & ALOOPER_EVENT_INPUT)) {
3850 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3851 "events=0x%x",
3852 connection->getInputChannelName().c_str(), events);
3853 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 }
3855
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003856 nsecs_t currentTime = now();
3857 bool gotOne = false;
3858 status_t status = OK;
3859 for (;;) {
3860 Result<InputPublisher::ConsumerResponse> result =
3861 connection->inputPublisher.receiveConsumerResponse();
3862 if (!result.ok()) {
3863 status = result.error().code();
3864 break;
3865 }
3866
3867 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3868 const InputPublisher::Finished& finish =
3869 std::get<InputPublisher::Finished>(*result);
3870 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3871 finish.consumeTime);
3872 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003873 if (shouldReportMetricsForConnection(*connection)) {
3874 const InputPublisher::Timeline& timeline =
3875 std::get<InputPublisher::Timeline>(*result);
3876 mLatencyTracker
3877 .trackGraphicsLatency(timeline.inputEventId,
3878 connection->inputChannel->getConnectionToken(),
3879 std::move(timeline.graphicsTimeline));
3880 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003881 }
3882 gotOne = true;
3883 }
3884 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003885 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003886 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 return 1;
3888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 }
3890
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003891 notify = status != DEAD_OBJECT || !connection->monitor;
3892 if (notify) {
3893 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3894 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3895 status);
3896 }
3897 } else {
3898 // Monitor channels are never explicitly unregistered.
3899 // We do it automatically when the remote endpoint is closed so don't warn about them.
3900 const bool stillHaveWindowHandle =
3901 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3902 notify = !connection->monitor && stillHaveWindowHandle;
3903 if (notify) {
3904 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3905 connection->getInputChannelName().c_str(), events);
3906 }
3907 }
3908
3909 // Remove the channel.
3910 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3911 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912}
3913
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003914void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003916 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003917 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 }
3919}
3920
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003922 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003923 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003924 for (const Monitor& monitor : monitors) {
3925 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003926 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003927 }
3928}
3929
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003931 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003932 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003933 if (connection == nullptr) {
3934 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003936
3937 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938}
3939
3940void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003941 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Lia4659fc2023-07-14 14:36:22 +08003942 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3943 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3944 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3945 LOG(INFO) << __func__
3946 << ": Canceling drag and drop because the pointers for the drag window are being "
3947 "canceled.";
3948 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3949 mDragState.reset();
3950 }
3951
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003952 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 return;
3954 }
3955
3956 nsecs_t currentTime = now();
3957
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003958 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003959 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003961 if (cancelationEvents.empty()) {
3962 return;
3963 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003964 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3965 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003966 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003967 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003968 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003969 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003970
Arthur Hungb3307ee2021-10-14 10:57:37 +00003971 std::string reason = std::string("reason=").append(options.reason);
3972 android_log_event_list(LOGTAG_INPUT_CANCEL)
3973 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3974
Svet Ganov5d3bc372020-01-26 23:11:07 -08003975 InputTarget target;
Hu Guoca59f112023-09-17 20:51:08 +08003976 sp<WindowInfoHandle> windowHandle;
3977 if (options.displayId) {
3978 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3979 options.displayId.value());
3980 } else {
3981 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3982 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003983 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003984 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003985 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003986 target.globalScaleFactor = windowInfo->globalScaleFactor;
3987 }
3988 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003989 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003990
hongzuo liu95785e22022-09-06 02:51:35 +00003991 const bool wasEmpty = connection->outboundQueue.empty();
3992
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003993 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003994 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003995 switch (cancelationEventEntry->type) {
3996 case EventEntry::Type::KEY: {
3997 logOutboundKeyDetails("cancel - ",
3998 static_cast<const KeyEntry&>(*cancelationEventEntry));
3999 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004001 case EventEntry::Type::MOTION: {
4002 logOutboundMotionDetails("cancel - ",
4003 static_cast<const MotionEntry&>(*cancelationEventEntry));
4004 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004006 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004007 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004008 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4009 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004010 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004011 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004012 break;
4013 }
4014 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004015 case EventEntry::Type::DEVICE_RESET:
4016 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004017 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004018 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004019 break;
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
4022
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004023 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004024 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004026
hongzuo liu95785e22022-09-06 02:51:35 +00004027 // If the outbound queue was previously empty, start the dispatch cycle going.
4028 if (wasEmpty && !connection->outboundQueue.empty()) {
4029 startDispatchCycleLocked(currentTime, connection);
4030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031}
4032
Svet Ganov5d3bc372020-01-26 23:11:07 -08004033void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004034 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004035 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004036 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004037 return;
4038 }
4039
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004040 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004041 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042
4043 if (downEvents.empty()) {
4044 return;
4045 }
4046
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004047 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004048 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4049 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004050 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004051
4052 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004053 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4055 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004056 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004057 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004058 target.globalScaleFactor = windowInfo->globalScaleFactor;
4059 }
4060 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004061 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004062
hongzuo liu95785e22022-09-06 02:51:35 +00004063 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004064 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004065 switch (downEventEntry->type) {
4066 case EventEntry::Type::MOTION: {
4067 logOutboundMotionDetails("down - ",
4068 static_cast<const MotionEntry&>(*downEventEntry));
4069 break;
4070 }
4071
4072 case EventEntry::Type::KEY:
4073 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004074 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004075 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004076 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004077 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004078 case EventEntry::Type::SENSOR:
4079 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004080 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004081 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004082 break;
4083 }
4084 }
4085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004086 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004087 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004088 }
4089
hongzuo liu95785e22022-09-06 02:51:35 +00004090 // If the outbound queue was previously empty, start the dispatch cycle going.
4091 if (wasEmpty && !connection->outboundQueue.empty()) {
4092 startDispatchCycleLocked(downTime, connection);
4093 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004094}
4095
Arthur Hungc539dbb2022-12-08 07:45:36 +00004096void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4097 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4098 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004099 std::shared_ptr<Connection> wallpaperConnection =
4100 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004101 if (wallpaperConnection != nullptr) {
4102 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4103 }
4104 }
4105}
4106
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004107std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004108 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4109 nsecs_t splitDownTime) {
4110 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
4112 uint32_t splitPointerIndexMap[MAX_POINTERS];
4113 PointerProperties splitPointerProperties[MAX_POINTERS];
4114 PointerCoords splitPointerCoords[MAX_POINTERS];
4115
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004116 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 uint32_t splitPointerCount = 0;
4118
4119 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004122 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004124 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4126 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4127 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004128 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 splitPointerCount += 1;
4130 }
4131 }
4132
4133 if (splitPointerCount != pointerIds.count()) {
4134 // This is bad. We are missing some of the pointers that we expected to deliver.
4135 // Most likely this indicates that we received an ACTION_MOVE events that has
4136 // different pointer ids than we expected based on the previous ACTION_DOWN
4137 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4138 // in this way.
4139 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004140 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004141 "a broken sequence of pointer ids from the input device: %s",
4142 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004143 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 }
4145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004146 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4149 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4151 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004152 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004154 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 if (pointerIds.count() == 1) {
4156 // The first/last pointer went down/up.
4157 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004158 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004159 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4160 ? AMOTION_EVENT_ACTION_CANCEL
4161 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 } else {
4163 // A secondary pointer went down/up.
4164 uint32_t splitPointerIndex = 0;
4165 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4166 splitPointerIndex += 1;
4167 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 action = maskedAction |
4169 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 }
4171 } else {
4172 // An unrelated pointer changed.
4173 action = AMOTION_EVENT_ACTION_MOVE;
4174 }
4175 }
4176
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004177 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4178 logDispatchStateLocked();
4179 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4180 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4181 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004182 }
4183
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004184 int32_t newId = mIdGenerator.nextId();
4185 if (ATRACE_ENABLED()) {
4186 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4187 ") to MotionEvent(id=0x%" PRIx32 ").",
4188 originalMotionEntry.id, newId);
4189 ATRACE_NAME(message.c_str());
4190 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004191 std::unique_ptr<MotionEntry> splitMotionEntry =
4192 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4193 originalMotionEntry.deviceId, originalMotionEntry.source,
4194 originalMotionEntry.displayId,
4195 originalMotionEntry.policyFlags, action,
4196 originalMotionEntry.actionButton,
4197 originalMotionEntry.flags, originalMotionEntry.metaState,
4198 originalMotionEntry.buttonState,
4199 originalMotionEntry.classification,
4200 originalMotionEntry.edgeFlags,
4201 originalMotionEntry.xPrecision,
4202 originalMotionEntry.yPrecision,
4203 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004204 originalMotionEntry.yCursorPosition, splitDownTime,
4205 splitPointerCount, splitPointerProperties,
4206 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004208 if (originalMotionEntry.injectionState) {
4209 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 splitMotionEntry->injectionState->refCount += 1;
4211 }
4212
4213 return splitMotionEntry;
4214}
4215
Prabir Pradhan678438e2023-04-13 19:32:51 +00004216void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004217 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004218 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220
Antonio Kantekf16f2832021-09-28 04:39:20 +00004221 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004223 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004225 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004226 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004227 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 } // release lock
4229
4230 if (needWake) {
4231 mLooper->wake();
4232 }
4233}
4234
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004235/**
4236 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004237 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4238 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4239 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4240 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4241 * potentially handle the back key presses.
4242 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4243 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004244 */
4245void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004247 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4248 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004249 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004250 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004251 }
4252 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004253 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004254 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004255 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004256 keyCode = newKeyCode;
4257 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4258 }
4259 } else if (action == AKEY_EVENT_ACTION_UP) {
4260 // In order to maintain a consistent stream of up and down events, check to see if the key
4261 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4262 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004263 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004264 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004265 auto replacementIt = mReplacedKeys.find(replacement);
4266 if (replacementIt != mReplacedKeys.end()) {
4267 keyCode = replacementIt->second;
4268 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004269 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4270 }
4271 }
4272}
4273
Prabir Pradhan678438e2023-04-13 19:32:51 +00004274void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004275 ALOGD_IF(debugInboundEventDetails(),
4276 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4277 ", deviceId=%d, source=%s, displayId=%" PRId32
4278 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4279 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004280 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4281 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4282 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004283 Result<void> keyCheck = validateKeyEvent(args.action);
4284 if (!keyCheck.ok()) {
4285 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 return;
4287 }
4288
Prabir Pradhan678438e2023-04-13 19:32:51 +00004289 uint32_t policyFlags = args.policyFlags;
4290 int32_t flags = args.flags;
4291 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004292 // InputDispatcher tracks and generates key repeats on behalf of
4293 // whatever notifies it, so repeatCount should always be set to 0
4294 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4296 policyFlags |= POLICY_FLAG_VIRTUAL;
4297 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 if (policyFlags & POLICY_FLAG_FUNCTION) {
4300 metaState |= AMETA_FUNCTION_ON;
4301 }
4302
4303 policyFlags |= POLICY_FLAG_TRUSTED;
4304
Prabir Pradhan678438e2023-04-13 19:32:51 +00004305 int32_t keyCode = args.keyCode;
4306 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004307
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004309 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4310 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4311 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
Michael Wright2b3c3302018-03-02 17:19:13 +00004313 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004314 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004315 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4316 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
Antonio Kantekf16f2832021-09-28 04:39:20 +00004320 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 { // acquire lock
4322 mLock.lock();
4323
4324 if (shouldSendKeyToInputFilterLocked(args)) {
4325 mLock.unlock();
4326
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004327 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004328 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 return; // event was consumed by the filter
4330 }
4331
4332 mLock.lock();
4333 }
4334
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004336 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4337 args.displayId, policyFlags, args.action, flags, keyCode,
4338 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004340 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 mLock.unlock();
4342 } // release lock
4343
4344 if (needWake) {
4345 mLooper->wake();
4346 }
4347}
4348
Prabir Pradhan678438e2023-04-13 19:32:51 +00004349bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 return mInputFilterEnabled;
4351}
4352
Prabir Pradhan678438e2023-04-13 19:32:51 +00004353void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004354 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004355 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004356 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004357 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4359 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004360 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4361 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4362 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4363 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4364 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004365 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004366 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4367 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004368 i, args.pointerProperties[i].id,
4369 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4370 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4371 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4372 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4373 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4374 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4375 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4376 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4377 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4378 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004381
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004382 Result<void> motionCheck =
4383 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4384 args.pointerProperties.data());
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004385 if (!motionCheck.ok()) {
4386 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004387 return;
4388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004390 if (DEBUG_VERIFY_EVENTS) {
4391 auto [it, _] =
4392 mVerifiersByDisplay.try_emplace(args.displayId,
4393 StringPrintf("display %" PRId32, args.displayId));
4394 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004395 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4396 args.pointerProperties.data(), args.pointerCoords.data(),
4397 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004398 if (!result.ok()) {
4399 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4400 }
4401 }
4402
Prabir Pradhan678438e2023-04-13 19:32:51 +00004403 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004405
4406 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004407 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004408 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4409 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412
Antonio Kantekf16f2832021-09-28 04:39:20 +00004413 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 { // acquire lock
4415 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004416 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4417 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4418 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004419 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004420 if (touchStateIt != mTouchStatesByDisplay.end()) {
4421 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004422 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004423 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4424 }
4425 }
4426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427
4428 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004429 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004430 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004431 displayTransform = it->second.transform;
4432 }
4433
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 mLock.unlock();
4435
4436 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004437 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4438 args.action, args.actionButton, args.flags, args.edgeFlags,
4439 args.metaState, args.buttonState, args.classification,
4440 displayTransform, args.xPrecision, args.yPrecision,
4441 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004442 args.downTime, args.eventTime, args.getPointerCount(),
4443 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444
4445 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004446 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 return; // event was consumed by the filter
4448 }
4449
4450 mLock.lock();
4451 }
4452
4453 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004454 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004455 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4456 args.displayId, policyFlags, args.action,
4457 args.actionButton, args.flags, args.metaState,
4458 args.buttonState, args.classification, args.edgeFlags,
4459 args.xPrecision, args.yPrecision,
4460 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004461 args.downTime, args.getPointerCount(),
4462 args.pointerProperties.data(),
4463 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
Prabir Pradhan678438e2023-04-13 19:32:51 +00004465 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4466 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004467 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004468 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4469 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004470 }
4471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004472 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473 mLock.unlock();
4474 } // release lock
4475
4476 if (needWake) {
4477 mLooper->wake();
4478 }
4479}
4480
Prabir Pradhan678438e2023-04-13 19:32:51 +00004481void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004482 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004483 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4484 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004485 args.id, args.eventTime, args.deviceId, args.source,
4486 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004487 }
Chris Yef59a2f42020-10-16 12:55:26 -07004488
Antonio Kantekf16f2832021-09-28 04:39:20 +00004489 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004490 { // acquire lock
4491 mLock.lock();
4492
4493 // Just enqueue a new sensor event.
4494 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004495 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4496 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4497 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004498
4499 needWake = enqueueInboundEventLocked(std::move(newEntry));
4500 mLock.unlock();
4501 } // release lock
4502
4503 if (needWake) {
4504 mLooper->wake();
4505 }
4506}
4507
Prabir Pradhan678438e2023-04-13 19:32:51 +00004508void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004509 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004510 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4511 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004512 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004513 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004514}
4515
Prabir Pradhan678438e2023-04-13 19:32:51 +00004516bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004517 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518}
4519
Prabir Pradhan678438e2023-04-13 19:32:51 +00004520void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004521 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004522 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4523 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004524 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
Prabir Pradhan678438e2023-04-13 19:32:51 +00004527 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004529 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530}
4531
Prabir Pradhan678438e2023-04-13 19:32:51 +00004532void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004533 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004534 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4535 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537
Antonio Kantekf16f2832021-09-28 04:39:20 +00004538 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004540 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004542 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004543 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004544 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 } // release lock
4546
4547 if (needWake) {
4548 mLooper->wake();
4549 }
4550}
4551
Prabir Pradhan678438e2023-04-13 19:32:51 +00004552void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004553 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004554 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4555 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004556 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004557
Antonio Kantekf16f2832021-09-28 04:39:20 +00004558 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004559 { // acquire lock
4560 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004561 auto entry =
4562 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004563 needWake = enqueueInboundEventLocked(std::move(entry));
4564 } // release lock
4565
4566 if (needWake) {
4567 mLooper->wake();
4568 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004569}
4570
Prabir Pradhan5735a322022-04-11 17:23:34 +00004571InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004572 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004573 InputEventInjectionSync syncMode,
4574 std::chrono::milliseconds timeout,
4575 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004576 Result<void> eventValidation = validateInputEvent(*event);
4577 if (!eventValidation.ok()) {
4578 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4579 return InputEventInjectionResult::FAILED;
4580 }
4581
Prabir Pradhan65613802023-02-22 23:36:58 +00004582 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004583 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004584 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4585 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4586 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004587 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004588 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
Prabir Pradhan5735a322022-04-11 17:23:34 +00004590 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004592 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004593 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4594 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4595 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4596 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4597 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004598 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004599 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004600 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004601 }
4602
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004603 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004605 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004606 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004607 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004608 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004609 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4610 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4611 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004612 int32_t keyCode = incomingKey.getKeyCode();
4613 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004614 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004616 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004617 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004618 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4619 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4620 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4623 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004624 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004625
4626 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4627 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004628 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004629 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4630 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4631 std::to_string(t.duration().count()).c_str());
4632 }
4633 }
4634
4635 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004636 std::unique_ptr<KeyEntry> injectedEntry =
4637 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004638 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004639 incomingKey.getDisplayId(), policyFlags, action,
4640 flags, keyCode, incomingKey.getScanCode(), metaState,
4641 incomingKey.getRepeatCount(),
4642 incomingKey.getDownTime());
4643 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004644 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004647 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004648 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004649 const bool isPointerEvent =
4650 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4651 // If a pointer event has no displayId specified, inject it to the default display.
4652 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4653 ? ADISPLAY_ID_DEFAULT
4654 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004655 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004656
4657 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004658 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004659 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004660 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004661 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4662 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4663 std::to_string(t.duration().count()).c_str());
4664 }
4665 }
4666
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004667 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4668 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4669 }
4670
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004671 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004672 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4673 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004674 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004675 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4676 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004677 displayId, policyFlags, motionEvent.getAction(),
4678 motionEvent.getActionButton(), flags,
4679 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004680 motionEvent.getButtonState(),
4681 motionEvent.getClassification(),
4682 motionEvent.getEdgeFlags(),
4683 motionEvent.getXPrecision(),
4684 motionEvent.getYPrecision(),
4685 motionEvent.getRawXCursorPosition(),
4686 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004687 motionEvent.getDownTime(),
4688 motionEvent.getPointerCount(),
4689 motionEvent.getPointerProperties(),
4690 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004691 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004692 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004693 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004694 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004695 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004696 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004697 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4698 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004699 displayId, policyFlags,
4700 motionEvent.getAction(),
4701 motionEvent.getActionButton(), flags,
4702 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004703 motionEvent.getButtonState(),
4704 motionEvent.getClassification(),
4705 motionEvent.getEdgeFlags(),
4706 motionEvent.getXPrecision(),
4707 motionEvent.getYPrecision(),
4708 motionEvent.getRawXCursorPosition(),
4709 motionEvent.getRawYCursorPosition(),
4710 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004711 motionEvent.getPointerCount(),
4712 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004713 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004714 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4715 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004716 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004717 }
4718 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004722 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004723 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
4725
Prabir Pradhan5735a322022-04-11 17:23:34 +00004726 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004727 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 injectionState->injectionIsAsync = true;
4729 }
4730
4731 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004732 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733
4734 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004735 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004736 if (DEBUG_INJECTION) {
4737 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4738 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004739 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004740 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 }
4742
4743 mLock.unlock();
4744
4745 if (needWake) {
4746 mLooper->wake();
4747 }
4748
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004749 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004751 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 if (syncMode == InputEventInjectionSync::NONE) {
4754 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 } else {
4756 for (;;) {
4757 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004758 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 break;
4760 }
4761
4762 nsecs_t remainingTimeout = endTime - now();
4763 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004764 if (DEBUG_INJECTION) {
4765 ALOGD("injectInputEvent - Timed out waiting for injection result "
4766 "to become available.");
4767 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004768 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 break;
4770 }
4771
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004772 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 }
4774
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004775 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4776 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004778 if (DEBUG_INJECTION) {
4779 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4780 injectionState->pendingForegroundDispatches);
4781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 nsecs_t remainingTimeout = endTime - now();
4783 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004784 if (DEBUG_INJECTION) {
4785 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4786 "dispatches to finish.");
4787 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 break;
4790 }
4791
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004792 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 }
4794 }
4795 }
4796
4797 injectionState->release();
4798 } // release lock
4799
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004800 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004801 LOG(DEBUG) << "injectInputEvent - Finished with result "
4802 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804
4805 return injectionResult;
4806}
4807
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004808std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004809 std::array<uint8_t, 32> calculatedHmac;
4810 std::unique_ptr<VerifiedInputEvent> result;
4811 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004812 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004813 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4814 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4815 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004816 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004817 break;
4818 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004819 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004820 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4821 VerifiedMotionEvent verifiedMotionEvent =
4822 verifiedMotionEventFromMotionEvent(motionEvent);
4823 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004824 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004825 break;
4826 }
4827 default: {
4828 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4829 return nullptr;
4830 }
4831 }
4832 if (calculatedHmac == INVALID_HMAC) {
4833 return nullptr;
4834 }
tyiu1573a672023-02-21 22:38:32 +00004835 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004836 return nullptr;
4837 }
4838 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004839}
4840
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004841void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004842 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004843 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004845 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004846 LOG(DEBUG) << "Setting input event injection result to "
4847 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004850 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 // Log the outcome since the injector did not wait for the injection result.
4852 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004853 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004854 ALOGV("Asynchronous input event injection succeeded.");
4855 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004856 case InputEventInjectionResult::TARGET_MISMATCH:
4857 ALOGV("Asynchronous input event injection target mismatch.");
4858 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004859 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 ALOGW("Asynchronous input event injection failed.");
4861 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004862 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004863 ALOGW("Asynchronous input event injection timed out.");
4864 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004865 case InputEventInjectionResult::PENDING:
4866 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4867 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869 }
4870
4871 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004872 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874}
4875
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004876void InputDispatcher::transformMotionEntryForInjectionLocked(
4877 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004878 // Input injection works in the logical display coordinate space, but the input pipeline works
4879 // display space, so we need to transform the injected events accordingly.
4880 const auto it = mDisplayInfos.find(entry.displayId);
4881 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004882 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004883
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004884 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4885 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4886 const vec2 cursor =
4887 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4888 {entry.xCursorPosition, entry.yCursorPosition});
4889 entry.xCursorPosition = cursor.x;
4890 entry.yCursorPosition = cursor.y;
4891 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004892 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004893 entry.pointerCoords[i] =
4894 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4895 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004896 }
4897}
4898
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004899void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4900 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 if (injectionState) {
4902 injectionState->pendingForegroundDispatches += 1;
4903 }
4904}
4905
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004906void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4907 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 if (injectionState) {
4909 injectionState->pendingForegroundDispatches -= 1;
4910
4911 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004912 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 }
4914 }
4915}
4916
chaviw98318de2021-05-19 16:45:23 -05004917const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004918 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004919 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004920 auto it = mWindowHandlesByDisplay.find(displayId);
4921 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004922}
4923
chaviw98318de2021-05-19 16:45:23 -05004924sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004925 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004926 if (windowHandleToken == nullptr) {
4927 return nullptr;
4928 }
4929
Arthur Hungb92218b2018-08-14 12:00:21 +08004930 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004931 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4932 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004933 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004934 return windowHandle;
4935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 }
4937 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004938 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939}
4940
chaviw98318de2021-05-19 16:45:23 -05004941sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4942 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004943 if (windowHandleToken == nullptr) {
4944 return nullptr;
4945 }
4946
chaviw98318de2021-05-19 16:45:23 -05004947 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004948 if (windowHandle->getToken() == windowHandleToken) {
4949 return windowHandle;
4950 }
4951 }
4952 return nullptr;
4953}
4954
chaviw98318de2021-05-19 16:45:23 -05004955sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4956 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004957 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004958 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4959 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004960 if (handle->getId() == windowHandle->getId() &&
4961 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004962 if (windowHandle->getInfo()->displayId != it.first) {
4963 ALOGE("Found window %s in display %" PRId32
4964 ", but it should belong to display %" PRId32,
4965 windowHandle->getName().c_str(), it.first,
4966 windowHandle->getInfo()->displayId);
4967 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004968 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 }
4971 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004972 return nullptr;
4973}
4974
chaviw98318de2021-05-19 16:45:23 -05004975sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004976 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4977 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978}
4979
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004980ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4981 auto displayInfoIt = mDisplayInfos.find(displayId);
4982 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4983 : kIdentityTransform;
4984}
4985
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004986bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4987 const MotionEntry& motionEntry) const {
4988 const WindowInfo& info = *window->getInfo();
4989
4990 // Skip spy window targets that are not valid for targeted injection.
4991 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004992 return false;
4993 }
4994
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004995 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4996 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4997 return false;
4998 }
4999
5000 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5001 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5002 window->getName().c_str());
5003 return false;
5004 }
5005
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005006 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005007 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005008 ALOGW("Not sending touch to %s because there's no corresponding connection",
5009 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005010 return false;
5011 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005012
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005013 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005014 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005015 return false;
5016 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005017
5018 // Drop events that can't be trusted due to occlusion
5019 const auto [x, y] = resolveTouchedPosition(motionEntry);
5020 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5021 if (!isTouchTrustedLocked(occlusionInfo)) {
5022 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005023 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005024 for (const auto& log : occlusionInfo.debugInfo) {
5025 ALOGD("%s", log.c_str());
5026 }
5027 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005028 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5029 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005030 return false;
5031 }
5032
5033 // Drop touch events if requested by input feature
5034 if (shouldDropInput(motionEntry, window)) {
5035 return false;
5036 }
5037
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005038 return true;
5039}
5040
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005041std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5042 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005043 auto connectionIt = mConnectionsByToken.find(token);
5044 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005045 return nullptr;
5046 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005047 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005048}
5049
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005050void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005051 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5052 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005053 // Remove all handles on a display if there are no windows left.
5054 mWindowHandlesByDisplay.erase(displayId);
5055 return;
5056 }
5057
5058 // Since we compare the pointer of input window handles across window updates, we need
5059 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005060 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5061 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5062 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005063 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005064 }
5065
chaviw98318de2021-05-19 16:45:23 -05005066 std::vector<sp<WindowInfoHandle>> newHandles;
5067 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005068 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005069 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005070 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005071 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005072 const bool canReceiveInput =
5073 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5074 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005075 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005076 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005077 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005078 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005079 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005080 }
5081
5082 if (info->displayId != displayId) {
5083 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5084 handle->getName().c_str(), displayId, info->displayId);
5085 continue;
5086 }
5087
Robert Carredd13602020-04-13 17:24:34 -07005088 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5089 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005090 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005091 oldHandle->updateFrom(handle);
5092 newHandles.push_back(oldHandle);
5093 } else {
5094 newHandles.push_back(handle);
5095 }
5096 }
5097
5098 // Insert or replace
5099 mWindowHandlesByDisplay[displayId] = newHandles;
5100}
5101
Arthur Hung72d8dc32020-03-28 00:48:39 +00005102void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005103 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005104 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005105 { // acquire lock
5106 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005107 for (const auto& [displayId, handles] : handlesPerDisplay) {
5108 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005109 }
5110 }
5111 // Wake up poll loop since it may need to make new input dispatching choices.
5112 mLooper->wake();
5113}
5114
Arthur Hungb92218b2018-08-14 12:00:21 +08005115/**
5116 * Called from InputManagerService, update window handle list by displayId that can receive input.
5117 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5118 * If set an empty list, remove all handles from the specific display.
5119 * For focused handle, check if need to change and send a cancel event to previous one.
5120 * For removed handle, check if need to send a cancel event if already in touch.
5121 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005122void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005123 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005124 if (DEBUG_FOCUS) {
5125 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005126 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005127 windowList += iwh->getName() + " ";
5128 }
5129 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Prabir Pradhand65552b2021-10-07 11:23:50 -07005132 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005133 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005134 const WindowInfo& info = *window->getInfo();
5135
5136 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005137 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005138 if (noInputWindow && window->getToken() != nullptr) {
5139 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5140 window->getName().c_str());
5141 window->releaseChannel();
5142 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005143
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005144 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005145 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5146 !info.inputConfig.test(
5147 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005148 "%s has feature SPY, but is not a trusted overlay.",
5149 window->getName().c_str());
5150
Prabir Pradhand65552b2021-10-07 11:23:50 -07005151 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005152 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5153 !info.inputConfig.test(
5154 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005155 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5156 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005157 }
5158
Arthur Hung72d8dc32020-03-28 00:48:39 +00005159 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005160 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005162 // Save the old windows' orientation by ID before it gets updated.
5163 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005164 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005165 oldWindowOrientations.emplace(handle->getId(),
5166 handle->getInfo()->transform.getOrientation());
5167 }
5168
chaviw98318de2021-05-19 16:45:23 -05005169 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005170
chaviw98318de2021-05-19 16:45:23 -05005171 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005172
Vishnu Nairc519ff72021-01-21 08:23:08 -08005173 std::optional<FocusResolver::FocusChanges> changes =
5174 mFocusResolver.setInputWindows(displayId, windowHandles);
5175 if (changes) {
5176 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005179 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5180 mTouchStatesByDisplay.find(displayId);
5181 if (stateIt != mTouchStatesByDisplay.end()) {
5182 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005183 for (size_t i = 0; i < state.windows.size();) {
5184 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005185 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005186 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005187 ALOGD("Touched window was removed: %s in display %" PRId32,
5188 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005189 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005190 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005191 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5192 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005193 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005194 "touched window was removed");
5195 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005196 // Since we are about to drop the touch, cancel the events for the wallpaper as
5197 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005198 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005199 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5200 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005201 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005202 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005205 state.windows.erase(state.windows.begin() + i);
5206 } else {
5207 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208 }
5209 }
arthurhungb89ccb02020-12-30 16:19:01 +08005210
arthurhung6d4bed92021-03-17 11:59:33 +08005211 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005212 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005213 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005214 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005215 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005216 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5217 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005218 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005219 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005220 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005221
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005222 // Determine if the orientation of any of the input windows have changed, and cancel all
5223 // pointer events if necessary.
5224 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5225 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5226 if (newWindowHandle != nullptr &&
5227 newWindowHandle->getInfo()->transform.getOrientation() !=
5228 oldWindowOrientations[oldWindowHandle->getId()]) {
5229 std::shared_ptr<InputChannel> inputChannel =
5230 getInputChannelLocked(newWindowHandle->getToken());
5231 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005232 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005233 "touched window's orientation changed");
5234 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005235 }
5236 }
5237 }
5238
Arthur Hung72d8dc32020-03-28 00:48:39 +00005239 // Release information for windows that are no longer present.
5240 // This ensures that unused input channels are released promptly.
5241 // Otherwise, they might stick around until the window handle is destroyed
5242 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005243 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005244 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005245 if (DEBUG_FOCUS) {
5246 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005247 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005248 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005249 }
chaviw291d88a2019-02-14 10:33:58 -08005250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251}
5252
5253void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005254 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005255 if (DEBUG_FOCUS) {
5256 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5257 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5258 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005259 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005260 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005261 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 } // release lock
5263
5264 // Wake up poll loop since it may need to make new input dispatching choices.
5265 mLooper->wake();
5266}
5267
Vishnu Nair599f1412021-06-21 10:39:58 -07005268void InputDispatcher::setFocusedApplicationLocked(
5269 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5270 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5271 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5272
5273 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5274 return; // This application is already focused. No need to wake up or change anything.
5275 }
5276
5277 // Set the new application handle.
5278 if (inputApplicationHandle != nullptr) {
5279 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5280 } else {
5281 mFocusedApplicationHandlesByDisplay.erase(displayId);
5282 }
5283
5284 // No matter what the old focused application was, stop waiting on it because it is
5285 // no longer focused.
5286 resetNoFocusedWindowTimeoutLocked();
5287}
5288
Tiger Huang721e26f2018-07-24 22:26:19 +08005289/**
5290 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5291 * the display not specified.
5292 *
5293 * We track any unreleased events for each window. If a window loses the ability to receive the
5294 * released event, we will send a cancel event to it. So when the focused display is changed, we
5295 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5296 * display. The display-specified events won't be affected.
5297 */
5298void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005299 if (DEBUG_FOCUS) {
5300 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5301 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005302 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005303 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005304
5305 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005306 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005307 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005308 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005309 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005310 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005311 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005312 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005313 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005314 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005315 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005316 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5317 }
5318 }
5319 mFocusedDisplayId = displayId;
5320
Chris Ye3c2d6f52020-08-09 10:39:48 -07005321 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005322 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005323 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005324
Vishnu Nairad321cd2020-08-20 16:40:21 -07005325 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005326 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005327 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005328 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005329 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005330 }
5331 }
5332 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005333 } // release lock
5334
5335 // Wake up poll loop since it may need to make new input dispatching choices.
5336 mLooper->wake();
5337}
5338
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005340 if (DEBUG_FOCUS) {
5341 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
5344 bool changed;
5345 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005346 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347
5348 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5349 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005350 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 }
5352
5353 if (mDispatchEnabled && !enabled) {
5354 resetAndDropEverythingLocked("dispatcher is being disabled");
5355 }
5356
5357 mDispatchEnabled = enabled;
5358 mDispatchFrozen = frozen;
5359 changed = true;
5360 } else {
5361 changed = false;
5362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 } // release lock
5364
5365 if (changed) {
5366 // Wake up poll loop since it may need to make new input dispatching choices.
5367 mLooper->wake();
5368 }
5369}
5370
5371void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005372 if (DEBUG_FOCUS) {
5373 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375
5376 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005377 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
5379 if (mInputFilterEnabled == enabled) {
5380 return;
5381 }
5382
5383 mInputFilterEnabled = enabled;
5384 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5385 } // release lock
5386
5387 // Wake up poll loop since there might be work to do to drop everything.
5388 mLooper->wake();
5389}
5390
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005391bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005392 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005393 bool needWake = false;
5394 {
5395 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005396 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005397 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005398 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005399 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5400 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005401 mTouchModePerDisplay.count(displayId) == 0
5402 ? "not set"
5403 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5404
Antonio Kantek15beb512022-06-13 22:35:41 +00005405 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5406 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005407 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005408 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005409 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005410 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5411 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005412 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005413 "window nor none of the previously interacted window",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005414 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005415 return false;
5416 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005417 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005418 mTouchModePerDisplay[displayId] = inTouchMode;
5419 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5420 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005421 needWake = enqueueInboundEventLocked(std::move(entry));
5422 } // release lock
5423
5424 if (needWake) {
5425 mLooper->wake();
5426 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005427 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005428}
5429
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005430bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005431 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5432 if (focusedToken == nullptr) {
5433 return false;
5434 }
5435 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5436 return isWindowOwnedBy(windowHandle, pid, uid);
5437}
5438
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005439bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005440 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5441 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5442 const sp<WindowInfoHandle> windowHandle =
5443 getWindowHandleLocked(connectionToken);
5444 return isWindowOwnedBy(windowHandle, pid, uid);
5445 }) != mInteractionConnectionTokens.end();
5446}
5447
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005448void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5449 if (opacity < 0 || opacity > 1) {
5450 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5451 return;
5452 }
5453
5454 std::scoped_lock lock(mLock);
5455 mMaximumObscuringOpacityForTouch = opacity;
5456}
5457
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005458std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5459InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005460 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5461 for (TouchedWindow& w : state.windows) {
5462 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005463 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005464 }
5465 }
5466 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005467 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005468}
5469
arthurhungb89ccb02020-12-30 16:19:01 +08005470bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5471 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005472 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005473 if (DEBUG_FOCUS) {
5474 ALOGD("Trivial transfer to same window.");
5475 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005476 return true;
5477 }
5478
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005480 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481
Arthur Hungabbb9d82021-09-01 14:52:30 +00005482 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005483 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005484
Arthur Hungabbb9d82021-09-01 14:52:30 +00005485 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005486 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 return false;
5488 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005489 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5490 if (deviceIds.size() != 1) {
5491 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5492 << " for window: " << touchedWindow->dump();
5493 return false;
5494 }
5495 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005496
Arthur Hungabbb9d82021-09-01 14:52:30 +00005497 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5498 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005499 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005500 return false;
5501 }
5502
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005503 if (DEBUG_FOCUS) {
5504 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005505 touchedWindow->windowHandle->getName().c_str(),
5506 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 }
5508
Arthur Hungabbb9d82021-09-01 14:52:30 +00005509 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005510 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005511 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005512 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005513 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514
Arthur Hungabbb9d82021-09-01 14:52:30 +00005515 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005516 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005517 ftl::Flags<InputTarget::Flags> newTargetFlags =
5518 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005519 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005520 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005521 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005522 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5523 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524
Arthur Hungabbb9d82021-09-01 14:52:30 +00005525 // Store the dragging window.
5526 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005527 if (pointerIds.count() != 1) {
5528 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5529 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005530 return false;
5531 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005532 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005533 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005534 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 }
5536
Arthur Hungabbb9d82021-09-01 14:52:30 +00005537 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005538 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5539 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005540 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005541 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005542 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5543 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005545 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5546 newTargetFlags);
5547
5548 // Check if the wallpaper window should deliver the corresponding event.
5549 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005550 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 } // release lock
5553
5554 // Wake up poll loop since it may need to make new input dispatching choices.
5555 mLooper->wake();
5556 return true;
5557}
5558
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005559/**
5560 * Get the touched foreground window on the given display.
5561 * Return null if there are no windows touched on that display, or if more than one foreground
5562 * window is being touched.
5563 */
5564sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5565 auto stateIt = mTouchStatesByDisplay.find(displayId);
5566 if (stateIt == mTouchStatesByDisplay.end()) {
5567 ALOGI("No touch state on display %" PRId32, displayId);
5568 return nullptr;
5569 }
5570
5571 const TouchState& state = stateIt->second;
5572 sp<WindowInfoHandle> touchedForegroundWindow;
5573 // If multiple foreground windows are touched, return nullptr
5574 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005575 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005576 if (touchedForegroundWindow != nullptr) {
5577 ALOGI("Two or more foreground windows: %s and %s",
5578 touchedForegroundWindow->getName().c_str(),
5579 window.windowHandle->getName().c_str());
5580 return nullptr;
5581 }
5582 touchedForegroundWindow = window.windowHandle;
5583 }
5584 }
5585 return touchedForegroundWindow;
5586}
5587
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005588// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005589bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005590 sp<IBinder> fromToken;
5591 { // acquire lock
5592 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005593 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005594 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005595 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5596 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005597 return false;
5598 }
5599
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005600 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5601 if (from == nullptr) {
5602 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5603 return false;
5604 }
5605
5606 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005607 } // release lock
5608
5609 return transferTouchFocus(fromToken, destChannelToken);
5610}
5611
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005613 if (DEBUG_FOCUS) {
5614 ALOGD("Resetting and dropping all events (%s).", reason);
5615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616
Michael Wrightfb04fd52022-11-24 22:31:11 +00005617 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 synthesizeCancelationEventsForAllConnectionsLocked(options);
5619
5620 resetKeyRepeatLocked();
5621 releasePendingEventLocked();
5622 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005623 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005625 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005626 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005627 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628}
5629
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005630void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005631 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 dumpDispatchStateLocked(dump);
5633
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005634 std::istringstream stream(dump);
5635 std::string line;
5636
5637 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005638 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 }
5640}
5641
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005642std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005643 std::string dump;
5644
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005645 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5646 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005647
5648 std::string windowName = "None";
5649 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005650 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005651 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5652 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5653 : "token has capture without window";
5654 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005655 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005656
5657 return dump;
5658}
5659
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005660void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005661 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5662 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5663 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005664 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665
Tiger Huang721e26f2018-07-24 22:26:19 +08005666 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5667 dump += StringPrintf(INDENT "FocusedApplications:\n");
5668 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5669 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005670 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005671 const std::chrono::duration timeout =
5672 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005673 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005674 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005675 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005678 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005680
Vishnu Nairc519ff72021-01-21 08:23:08 -08005681 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005682 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005684 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005685 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005686 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005687 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5688 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 }
5690 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005691 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 }
5693
arthurhung6d4bed92021-03-17 11:59:33 +08005694 if (mDragState) {
5695 dump += StringPrintf(INDENT "DragState:\n");
5696 mDragState->dump(dump, INDENT2);
5697 }
5698
Arthur Hungb92218b2018-08-14 12:00:21 +08005699 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005700 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5701 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5702 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5703 const auto& displayInfo = it->second;
5704 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5705 displayInfo.logicalHeight);
5706 displayInfo.transform.dump(dump, "transform", INDENT4);
5707 } else {
5708 dump += INDENT2 "No DisplayInfo found!\n";
5709 }
5710
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005711 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005712 dump += INDENT2 "Windows:\n";
5713 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005714 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5715 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005717 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005718 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005719 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005720 "applicationInfo.name=%s, "
5721 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005722 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005723 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005724 windowInfo->displayId,
5725 windowInfo->inputConfig.string().c_str(),
5726 windowInfo->alpha, windowInfo->frameLeft,
5727 windowInfo->frameTop, windowInfo->frameRight,
5728 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005729 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005730 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005731 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005732 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005733 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005734 "touchOcclusionMode=%s\n",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005735 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005736 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005737 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005738 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005739 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005740 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005741 }
5742 } else {
5743 dump += INDENT2 "Windows: <none>\n";
5744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745 }
5746 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005747 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 }
5749
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005750 if (!mGlobalMonitorsByDisplay.empty()) {
5751 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5752 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005753 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005756 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757 }
5758
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005759 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760
5761 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005762 if (!mRecentQueue.empty()) {
5763 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005764 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005765 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005766 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005767 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 }
5769 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005770 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 }
5772
5773 // Dump event currently being dispatched.
5774 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT "PendingEvent:\n";
5776 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005777 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005778 dump += StringPrintf(", age=%" PRId64 "ms\n",
5779 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 }
5783
5784 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005785 if (!mInboundQueue.empty()) {
5786 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005787 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005788 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005789 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005790 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
5792 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005793 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 }
5795
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005796 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005797 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005798 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005799 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005800 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005801 }
5802 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005803 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005804 }
5805
Prabir Pradhancef936d2021-07-21 16:17:52 +00005806 if (!mCommandQueue.empty()) {
5807 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5808 } else {
5809 dump += INDENT "CommandQueue: <empty>\n";
5810 }
5811
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005812 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005813 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005814 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005815 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005816 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005817 connection->inputChannel->getFd().get(),
5818 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005819 connection->getWindowName().c_str(),
5820 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005821 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005823 if (!connection->outboundQueue.empty()) {
5824 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5825 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005826 dump += dumpQueue(connection->outboundQueue, currentTime);
5827
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005829 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 }
5831
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005832 if (!connection->waitQueue.empty()) {
5833 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5834 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005835 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005837 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838 }
5839 }
5840 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005841 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 }
5843
5844 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005845 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5846 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005848 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 }
5850
Antonio Kantek15beb512022-06-13 22:35:41 +00005851 if (!mTouchModePerDisplay.empty()) {
5852 dump += INDENT "TouchModePerDisplay:\n";
5853 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5854 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5855 std::to_string(touchMode).c_str());
5856 }
5857 } else {
5858 dump += INDENT "TouchModePerDisplay: <none>\n";
5859 }
5860
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005861 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005862 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5863 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5864 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005865 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005866 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867}
5868
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005869void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005870 const size_t numMonitors = monitors.size();
5871 for (size_t i = 0; i < numMonitors; i++) {
5872 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005873 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005874 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5875 dump += "\n";
5876 }
5877}
5878
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005879class LooperEventCallback : public LooperCallback {
5880public:
5881 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5882 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5883
5884private:
5885 std::function<int(int events)> mCallback;
5886};
5887
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005888Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005889 if (DEBUG_CHANNEL_CREATION) {
5890 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005893 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005894 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005895 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005896
5897 if (result) {
5898 return base::Error(result) << "Failed to open input channel pair with name " << name;
5899 }
5900
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005902 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005903 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005904 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005905 std::shared_ptr<Connection> connection =
5906 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5907 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005909 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5910 ALOGE("Created a new connection, but the token %p is already known", token.get());
5911 }
5912 mConnectionsByToken.emplace(token, connection);
5913
5914 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5915 this, std::placeholders::_1, token);
5916
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005917 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005918 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 } // release lock
5920
5921 // Wake the looper because some connections have changed.
5922 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005923 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924}
5925
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005926Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005927 const std::string& name,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005928 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005929 std::shared_ptr<InputChannel> serverChannel;
5930 std::unique_ptr<InputChannel> clientChannel;
5931 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5932 if (result) {
5933 return base::Error(result) << "Failed to open input channel pair with name " << name;
5934 }
5935
Michael Wright3dd60e22019-03-27 22:06:44 +00005936 { // acquire lock
5937 std::scoped_lock _l(mLock);
5938
5939 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005940 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5941 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005942 }
5943
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005944 std::shared_ptr<Connection> connection =
5945 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005946 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005947 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005948
5949 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5950 ALOGE("Created a new connection, but the token %p is already known", token.get());
5951 }
5952 mConnectionsByToken.emplace(token, connection);
5953 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5954 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005955
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005956 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005957
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005958 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005959 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005960 }
Garfield Tan15601662020-09-22 15:32:38 -07005961
Michael Wright3dd60e22019-03-27 22:06:44 +00005962 // Wake the looper because some connections have changed.
5963 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005964 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005965}
5966
Garfield Tan15601662020-09-22 15:32:38 -07005967status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005969 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970
Harry Cutts33476232023-01-30 19:57:29 +00005971 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 if (status) {
5973 return status;
5974 }
5975 } // release lock
5976
5977 // Wake the poll loop because removing the connection may have changed the current
5978 // synchronization state.
5979 mLooper->wake();
5980 return OK;
5981}
5982
Garfield Tan15601662020-09-22 15:32:38 -07005983status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5984 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005985 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005986 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005987 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988 return BAD_VALUE;
5989 }
5990
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005991 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005992
Michael Wrightd02c5b62014-02-10 15:10:22 -08005993 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005994 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 }
5996
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005997 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998
5999 nsecs_t currentTime = now();
6000 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6001
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006002 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003 return OK;
6004}
6005
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006006void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006007 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6008 auto& [displayId, monitors] = *it;
6009 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6010 return monitor.inputChannel->getConnectionToken() == connectionToken;
6011 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006012
Michael Wright3dd60e22019-03-27 22:06:44 +00006013 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006014 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006015 } else {
6016 ++it;
6017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 }
6019}
6020
Michael Wright3dd60e22019-03-27 22:06:44 +00006021status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006022 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006023 return pilferPointersLocked(token);
6024}
Michael Wright3dd60e22019-03-27 22:06:44 +00006025
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006026status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006027 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6028 if (!requestingChannel) {
6029 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
6030 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006031 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006032
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006033 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006034 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006035 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
6036 " Ignoring.");
6037 return BAD_VALUE;
6038 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006039 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
6040 if (deviceIds.size() != 1) {
6041 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
6042 << " in window: " << windowPtr->dump();
6043 return BAD_VALUE;
6044 }
6045 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006046
6047 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006048 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006049 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00006050 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006051 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006052 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006053 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006054 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6055 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006056 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006057 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006058 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006059 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006060 if (channel != nullptr && channel->getConnectionToken() != token) {
6061 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6062 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6063 canceledWindows += channel->getName();
6064 }
6065 }
6066 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6067 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6068 canceledWindows.c_str());
6069
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006070 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006071 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006072 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006073
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006074 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006075 return OK;
6076}
6077
Prabir Pradhan99987712020-11-10 18:43:05 -08006078void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6079 { // acquire lock
6080 std::scoped_lock _l(mLock);
6081 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006082 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006083 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6084 windowHandle != nullptr ? windowHandle->getName().c_str()
6085 : "token without window");
6086 }
6087
Vishnu Nairc519ff72021-01-21 08:23:08 -08006088 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006089 if (focusedToken != windowToken) {
6090 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6091 enabled ? "enable" : "disable");
6092 return;
6093 }
6094
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006095 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006096 ALOGW("Ignoring request to %s Pointer Capture: "
6097 "window has %s requested pointer capture.",
6098 enabled ? "enable" : "disable", enabled ? "already" : "not");
6099 return;
6100 }
6101
Christine Franksb768bb42021-11-29 12:11:31 -08006102 if (enabled) {
6103 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6104 mIneligibleDisplaysForPointerCapture.end(),
6105 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6106 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6107 return;
6108 }
6109 }
6110
Prabir Pradhan99987712020-11-10 18:43:05 -08006111 setPointerCaptureLocked(enabled);
6112 } // release lock
6113
6114 // Wake the thread to process command entries.
6115 mLooper->wake();
6116}
6117
Christine Franksb768bb42021-11-29 12:11:31 -08006118void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6119 { // acquire lock
6120 std::scoped_lock _l(mLock);
6121 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6122 if (!isEligible) {
6123 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6124 }
6125 } // release lock
6126}
6127
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006128std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006129 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006130 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006131 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006132 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006133 }
6134 }
6135 }
6136 return std::nullopt;
6137}
6138
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006139std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6140 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006141 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006142 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006143 }
6144
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006145 for (const auto& [token, connection] : mConnectionsByToken) {
6146 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006147 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148 }
6149 }
Robert Carr4e670e52018-08-15 13:26:12 -07006150
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006151 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006152}
6153
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006154std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006155 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006156 if (connection == nullptr) {
6157 return "<nullptr>";
6158 }
6159 return connection->getInputChannelName();
6160}
6161
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006162void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006163 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006164 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006165}
6166
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006168 const std::shared_ptr<Connection>& connection,
6169 uint32_t seq, bool handled,
6170 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171 // Handle post-event policy actions.
6172 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6173 if (dispatchEntryIt == connection->waitQueue.end()) {
6174 return;
6175 }
6176 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6177 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6178 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6179 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6180 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6181 }
6182 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6183 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6184 connection->inputChannel->getConnectionToken(),
6185 dispatchEntry->deliveryTime, consumeTime, finishTime);
6186 }
6187
6188 bool restartEvent;
6189 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6190 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6191 restartEvent =
6192 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6193 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6194 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6195 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6196 handled);
6197 } else {
6198 restartEvent = false;
6199 }
6200
6201 // Dequeue the event and start the next cycle.
6202 // Because the lock might have been released, it is possible that the
6203 // contents of the wait queue to have been drained, so we need to double-check
6204 // a few things.
6205 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6206 if (dispatchEntryIt != connection->waitQueue.end()) {
6207 dispatchEntry = *dispatchEntryIt;
6208 connection->waitQueue.erase(dispatchEntryIt);
6209 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6210 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6211 if (!connection->responsive) {
6212 connection->responsive = isConnectionResponsive(*connection);
6213 if (connection->responsive) {
6214 // The connection was unresponsive, and now it's responsive.
6215 processConnectionResponsiveLocked(*connection);
6216 }
6217 }
6218 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006219 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006220 connection->outboundQueue.push_front(dispatchEntry);
6221 traceOutboundQueueLength(*connection);
6222 } else {
6223 releaseDispatchEntry(dispatchEntry);
6224 }
6225 }
6226
6227 // Start the next dispatch cycle for this connection.
6228 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229}
6230
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6232 const sp<IBinder>& newToken) {
6233 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6234 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006235 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006236 };
6237 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238}
6239
Prabir Pradhancef936d2021-07-21 16:17:52 +00006240void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6241 auto command = [this, token, x, y]() REQUIRES(mLock) {
6242 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006243 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006244 };
6245 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006246}
6247
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006248void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006249 if (connection == nullptr) {
6250 LOG_ALWAYS_FATAL("Caller must check for nullness");
6251 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006252 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6253 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006254 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006255 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006256 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006257 return;
6258 }
6259 /**
6260 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6261 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6262 * has changed. This could cause newer entries to time out before the already dispatched
6263 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6264 * processes the events linearly. So providing information about the oldest entry seems to be
6265 * most useful.
6266 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006267 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006268 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6269 std::string reason =
6270 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006271 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006272 ns2ms(currentWait),
6273 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006274 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006275 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006276
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006277 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6278
6279 // Stop waking up for events on this connection, it is already unresponsive
6280 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006281}
6282
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006283void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6284 std::string reason =
6285 StringPrintf("%s does not have a focused window", application->getName().c_str());
6286 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006287
Yabin Cui8eb9c552023-06-08 18:05:07 +00006288 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006289 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006290 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006291 };
6292 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006293}
6294
chaviw98318de2021-05-19 16:45:23 -05006295void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006296 const std::string& reason) {
6297 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6298 updateLastAnrStateLocked(windowLabel, reason);
6299}
6300
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006301void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6302 const std::string& reason) {
6303 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006304 updateLastAnrStateLocked(windowLabel, reason);
6305}
6306
6307void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6308 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006310 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311 struct tm tm;
6312 localtime_r(&t, &tm);
6313 char timestr[64];
6314 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006315 mLastAnrState.clear();
6316 mLastAnrState += INDENT "ANR:\n";
6317 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006318 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6319 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006320 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321}
6322
Prabir Pradhancef936d2021-07-21 16:17:52 +00006323void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6324 KeyEntry& entry) {
6325 const KeyEvent event = createKeyEvent(entry);
6326 nsecs_t delay = 0;
6327 { // release lock
6328 scoped_unlock unlock(mLock);
6329 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006330 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6332 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6333 std::to_string(t.duration().count()).c_str());
6334 }
6335 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336
6337 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006338 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006339 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006340 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006341 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006342 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006343 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345}
6346
Prabir Pradhancef936d2021-07-21 16:17:52 +00006347void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006348 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006349 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006350 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006351 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006352 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006353 };
6354 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006355}
6356
Prabir Pradhanedd96402022-02-15 01:46:16 -08006357void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006358 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006359 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006360 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006361 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006362 };
6363 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006364}
6365
6366/**
6367 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6368 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6369 * command entry to the command queue.
6370 */
6371void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6372 std::string reason) {
6373 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006374 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006375 if (connection.monitor) {
6376 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6377 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006378 pid = findMonitorPidByTokenLocked(connectionToken);
6379 } else {
6380 // The connection is a window
6381 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6382 reason.c_str());
6383 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6384 if (handle != nullptr) {
6385 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006386 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006387 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006388 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006389}
6390
6391/**
6392 * Tell the policy that a connection has become responsive so that it can stop ANR.
6393 */
6394void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6395 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006396 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006397 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006398 pid = findMonitorPidByTokenLocked(connectionToken);
6399 } else {
6400 // The connection is a window
6401 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6402 if (handle != nullptr) {
6403 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006404 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006405 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006406 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006407}
6408
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006409bool InputDispatcher::afterKeyEventLockedInterruptable(
6410 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6411 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006412 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006413 if (!handled) {
6414 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006415 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006416 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 return false;
6418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006420 // Get the fallback key state.
6421 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006422 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006423 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006424 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425 connection->inputState.removeFallbackKey(originalKeyCode);
6426 }
6427
6428 if (handled || !dispatchEntry->hasForegroundTarget()) {
6429 // If the application handles the original key for which we previously
6430 // generated a fallback or if the window is not a foreground window,
6431 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006432 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006433 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006434 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6435 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6436 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6437 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6438 keyEntry.policyFlags);
6439 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006440 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442
6443 mLock.unlock();
6444
Prabir Pradhana41d2442023-04-20 21:30:40 +00006445 if (const auto unhandledKeyFallback =
6446 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6447 event, keyEntry.policyFlags);
6448 unhandledKeyFallback) {
6449 event = *unhandledKeyFallback;
6450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451
6452 mLock.lock();
6453
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006454 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006455 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006456 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 "application handled the original non-fallback key "
6458 "or is no longer a foreground target, "
6459 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006460 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006462 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 connection->inputState.removeFallbackKey(originalKeyCode);
6464 }
6465 } else {
6466 // If the application did not handle a non-fallback key, first check
6467 // that we are in a good state to perform unhandled key event processing
6468 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006469 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006470 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006471 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6472 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6473 "since this is not an initial down. "
6474 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6475 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6476 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006477 return false;
6478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006479
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006481 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6482 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6483 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6484 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6485 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006486 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487
6488 mLock.unlock();
6489
Prabir Pradhana41d2442023-04-20 21:30:40 +00006490 bool fallback = false;
6491 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6492 event, keyEntry.policyFlags);
6493 fb) {
6494 fallback = true;
6495 event = *fb;
6496 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006497
6498 mLock.lock();
6499
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006500 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501 connection->inputState.removeFallbackKey(originalKeyCode);
6502 return false;
6503 }
6504
6505 // Latch the fallback keycode for this key on an initial down.
6506 // The fallback keycode cannot change at any other point in the lifecycle.
6507 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006509 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006510 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006511 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006513 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006514 }
6515
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006516 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517
6518 // Cancel the fallback key if the policy decides not to send it anymore.
6519 // We will continue to dispatch the key to the policy but we will no
6520 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006521 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6522 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006523 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6524 if (fallback) {
6525 ALOGD("Unhandled key event: Policy requested to send key %d"
6526 "as a fallback for %d, but on the DOWN it had requested "
6527 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006528 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006529 } else {
6530 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6531 "but on the DOWN it had requested to send %d. "
6532 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006533 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006534 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006535 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006536
Michael Wrightfb04fd52022-11-24 22:31:11 +00006537 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006539 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006540 synthesizeCancelationEventsForConnectionLocked(connection, options);
6541
6542 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006543 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006544 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006545 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006546 }
6547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006549 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6550 {
6551 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006552 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006553 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006554 for (const auto& [key, value] : fallbackKeys) {
6555 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006556 }
6557 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6558 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006559 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006560 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006561
6562 if (fallback) {
6563 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006564 keyEntry.eventTime = event.getEventTime();
6565 keyEntry.deviceId = event.getDeviceId();
6566 keyEntry.source = event.getSource();
6567 keyEntry.displayId = event.getDisplayId();
6568 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006569 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006570 keyEntry.scanCode = event.getScanCode();
6571 keyEntry.metaState = event.getMetaState();
6572 keyEntry.repeatCount = event.getRepeatCount();
6573 keyEntry.downTime = event.getDownTime();
6574 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006575
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006576 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6577 ALOGD("Unhandled key event: Dispatching fallback key. "
6578 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006579 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006580 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 return true; // restart the event
6582 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6584 ALOGD("Unhandled key event: No fallback key.");
6585 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006586
6587 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006588 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 }
6590 }
6591 return false;
6592}
6593
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006594bool InputDispatcher::afterMotionEventLockedInterruptable(
6595 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6596 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597 return false;
6598}
6599
Michael Wrightd02c5b62014-02-10 15:10:22 -08006600void InputDispatcher::traceInboundQueueLengthLocked() {
6601 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006602 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603 }
6604}
6605
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006606void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607 if (ATRACE_ENABLED()) {
6608 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006609 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6610 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006611 }
6612}
6613
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006614void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 if (ATRACE_ENABLED()) {
6616 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006617 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6618 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619 }
6620}
6621
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006622void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006623 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006625 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006626 dumpDispatchStateLocked(dump);
6627
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006628 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006629 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006630 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 }
6632}
6633
6634void InputDispatcher::monitor() {
6635 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006636 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006638 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639}
6640
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006641/**
6642 * Wake up the dispatcher and wait until it processes all events and commands.
6643 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6644 * this method can be safely called from any thread, as long as you've ensured that
6645 * the work you are interested in completing has already been queued.
6646 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006647bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006648 /**
6649 * Timeout should represent the longest possible time that a device might spend processing
6650 * events and commands.
6651 */
6652 constexpr std::chrono::duration TIMEOUT = 100ms;
6653 std::unique_lock lock(mLock);
6654 mLooper->wake();
6655 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6656 return result == std::cv_status::no_timeout;
6657}
6658
Vishnu Naire798b472020-07-23 13:52:21 -07006659/**
6660 * Sets focus to the window identified by the token. This must be called
6661 * after updating any input window handles.
6662 *
6663 * Params:
6664 * request.token - input channel token used to identify the window that should gain focus.
6665 * request.focusedToken - the token that the caller expects currently to be focused. If the
6666 * specified token does not match the currently focused window, this request will be dropped.
6667 * If the specified focused token matches the currently focused window, the call will succeed.
6668 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6669 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6670 * when requesting the focus change. This determines which request gets
6671 * precedence if there is a focus change request from another source such as pointer down.
6672 */
Vishnu Nair958da932020-08-21 17:12:37 -07006673void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6674 { // acquire lock
6675 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006676 std::optional<FocusResolver::FocusChanges> changes =
6677 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6678 if (changes) {
6679 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006680 }
6681 } // release lock
6682 // Wake up poll loop since it may need to make new input dispatching choices.
6683 mLooper->wake();
6684}
6685
Vishnu Nairc519ff72021-01-21 08:23:08 -08006686void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6687 if (changes.oldFocus) {
6688 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006689 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006690 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006691 "focus left window");
6692 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006693 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006694 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006695 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006696 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006697 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006698 }
6699
Prabir Pradhan99987712020-11-10 18:43:05 -08006700 // If a window has pointer capture, then it must have focus. We need to ensure that this
6701 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6702 // If the window loses focus before it loses pointer capture, then the window can be in a state
6703 // where it has pointer capture but not focus, violating the contract. Therefore we must
6704 // dispatch the pointer capture event before the focus event. Since focus events are added to
6705 // the front of the queue (above), we add the pointer capture event to the front of the queue
6706 // after the focus events are added. This ensures the pointer capture event ends up at the
6707 // front.
6708 disablePointerCaptureForcedLocked();
6709
Vishnu Nairc519ff72021-01-21 08:23:08 -08006710 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006711 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006712 }
6713}
Vishnu Nair958da932020-08-21 17:12:37 -07006714
Prabir Pradhan99987712020-11-10 18:43:05 -08006715void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006716 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006717 return;
6718 }
6719
6720 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6721
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006722 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006723 setPointerCaptureLocked(false);
6724 }
6725
6726 if (!mWindowTokenWithPointerCapture) {
6727 // No need to send capture changes because no window has capture.
6728 return;
6729 }
6730
6731 if (mPendingEvent != nullptr) {
6732 // Move the pending event to the front of the queue. This will give the chance
6733 // for the pending event to be dropped if it is a captured event.
6734 mInboundQueue.push_front(mPendingEvent);
6735 mPendingEvent = nullptr;
6736 }
6737
6738 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006739 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006740 mInboundQueue.push_front(std::move(entry));
6741}
6742
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006743void InputDispatcher::setPointerCaptureLocked(bool enable) {
6744 mCurrentPointerCaptureRequest.enable = enable;
6745 mCurrentPointerCaptureRequest.seq++;
6746 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006747 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006748 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006749 };
6750 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006751}
6752
Vishnu Nair599f1412021-06-21 10:39:58 -07006753void InputDispatcher::displayRemoved(int32_t displayId) {
6754 { // acquire lock
6755 std::scoped_lock _l(mLock);
6756 // Set an empty list to remove all handles from the specific display.
6757 setInputWindowsLocked(/* window handles */ {}, displayId);
6758 setFocusedApplicationLocked(displayId, nullptr);
6759 // Call focus resolver to clean up stale requests. This must be called after input windows
6760 // have been removed for the removed display.
6761 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006762 // Reset pointer capture eligibility, regardless of previous state.
6763 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006764 // Remove the associated touch mode state.
6765 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006766 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006767 } // release lock
6768
6769 // Wake up poll loop since it may need to make new input dispatching choices.
6770 mLooper->wake();
6771}
6772
Patrick Williamsd828f302023-04-28 17:52:08 -05006773void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006774 // The listener sends the windows as a flattened array. Separate the windows by display for
6775 // more convenient parsing.
6776 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006777 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006778 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006779 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006780 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006781
6782 { // acquire lock
6783 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006784
6785 // Ensure that we have an entry created for all existing displays so that if a displayId has
6786 // no windows, we can tell that the windows were removed from the display.
6787 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6788 handlesPerDisplay[displayId];
6789 }
6790
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006791 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006792 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006793 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6794 }
6795
6796 for (const auto& [displayId, handles] : handlesPerDisplay) {
6797 setInputWindowsLocked(handles, displayId);
6798 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006799
6800 if (update.vsyncId < mWindowInfosVsyncId) {
6801 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6802 ", current update vsync id: %" PRId64,
6803 mWindowInfosVsyncId, update.vsyncId);
6804 }
6805 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006806 }
6807 // Wake up poll loop since it may need to make new input dispatching choices.
6808 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006809}
6810
Vishnu Nair062a8672021-09-03 16:07:44 -07006811bool InputDispatcher::shouldDropInput(
6812 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006813 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6814 (windowHandle->getInfo()->inputConfig.test(
6815 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006816 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006817 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6818 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006819 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006820 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006821 windowHandle->getInfo()->displayId);
6822 return true;
6823 }
6824 return false;
6825}
6826
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006827void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006828 const gui::WindowInfosUpdate& update) {
6829 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006830}
6831
Arthur Hungdfd528e2021-12-08 13:23:04 +00006832void InputDispatcher::cancelCurrentTouch() {
6833 {
6834 std::scoped_lock _l(mLock);
6835 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006836 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006837 "cancel current touch");
6838 synthesizeCancelationEventsForAllConnectionsLocked(options);
6839
6840 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006841 }
6842 // Wake up poll loop since there might be work to do.
6843 mLooper->wake();
6844}
6845
Prabir Pradhan87112a72023-04-20 19:13:39 +00006846void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006847 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006848
6849 std::scoped_lock _l(mLock);
6850 mConfig = config;
6851}
6852
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006853void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6854 std::scoped_lock _l(mLock);
6855 mMonitorDispatchingTimeout = timeout;
6856}
6857
Arthur Hungc539dbb2022-12-08 07:45:36 +00006858void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6859 const sp<WindowInfoHandle>& oldWindowHandle,
6860 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006861 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006862 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006863 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6864 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006865 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6866 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6867 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6868 newWindowHandle->getInfo()->inputConfig.test(
6869 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6870 const sp<WindowInfoHandle> oldWallpaper =
6871 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6872 const sp<WindowInfoHandle> newWallpaper =
6873 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6874 if (oldWallpaper == newWallpaper) {
6875 return;
6876 }
6877
6878 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006879 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6880 addWindowTargetLocked(oldWallpaper,
6881 oldTouchedWindow.targetFlags |
6882 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006883 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6884 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006885 }
6886
6887 if (newWallpaper != nullptr) {
6888 state.addOrUpdateWindow(newWallpaper,
6889 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6890 InputTarget::Flags::WINDOW_IS_OBSCURED |
6891 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006892 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006893 }
6894}
6895
6896void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6897 ftl::Flags<InputTarget::Flags> newTargetFlags,
6898 const sp<WindowInfoHandle> fromWindowHandle,
6899 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006900 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006901 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006902 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6903 fromWindowHandle->getInfo()->inputConfig.test(
6904 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6905 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6906 toWindowHandle->getInfo()->inputConfig.test(
6907 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6908
6909 const sp<WindowInfoHandle> oldWallpaper =
6910 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6911 const sp<WindowInfoHandle> newWallpaper =
6912 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6913 if (oldWallpaper == newWallpaper) {
6914 return;
6915 }
6916
6917 if (oldWallpaper != nullptr) {
6918 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6919 "transferring touch focus to another window");
6920 state.removeWindowByToken(oldWallpaper->getToken());
6921 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6922 }
6923
6924 if (newWallpaper != nullptr) {
6925 nsecs_t downTimeInTarget = now();
6926 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6927 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6928 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6929 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006930 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6931 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006932 std::shared_ptr<Connection> wallpaperConnection =
6933 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006934 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006935 std::shared_ptr<Connection> toConnection =
6936 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006937 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6938 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6939 wallpaperFlags);
6940 }
6941 }
6942}
6943
6944sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6945 const sp<WindowInfoHandle>& windowHandle) const {
6946 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6947 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6948 bool foundWindow = false;
6949 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6950 if (!foundWindow && otherHandle != windowHandle) {
6951 continue;
6952 }
6953 if (windowHandle == otherHandle) {
6954 foundWindow = true;
6955 continue;
6956 }
6957
6958 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6959 return otherHandle;
6960 }
6961 }
6962 return nullptr;
6963}
6964
Garfield Tane84e6f92019-08-29 17:28:41 -07006965} // namespace android::inputdispatcher