blob: 020fca0d4671186d20c597024f3d12dff529f37c [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070029#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070032#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080033#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080034#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000035#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010037#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Michael Wright44753b12020-07-08 13:48:11 +010040#include <cerrno>
41#include <cinttypes>
42#include <climits>
43#include <cstddef>
44#include <ctime>
45#include <queue>
46#include <sstream>
47
48#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000049#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070050#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#define INDENT " "
53#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
56
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080057using namespace android::ftl::flag_operators;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -070058using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080059using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000060using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070062using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050063using android::gui::FocusRequest;
64using android::gui::TouchOcclusionMode;
65using android::gui::WindowInfo;
66using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080067using android::os::InputEventInjectionResult;
68using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069
Garfield Tane84e6f92019-08-29 17:28:41 -070070namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080071
Prabir Pradhancef936d2021-07-21 16:17:52 +000072namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000073// Temporarily releases a held mutex for the lifetime of the instance.
74// Named to match std::scoped_lock
75class scoped_unlock {
76public:
77 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
78 ~scoped_unlock() { mMutex.lock(); }
79
80private:
81 std::mutex& mMutex;
82};
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// Default input dispatching timeout if there is no focused application or paused window
85// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080086const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
87 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
88 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for all pending events to be processed when an app switch
91// key is on the way. This is used to preempt input dispatch and drop input events
92// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080095const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Antonio Kantekea47acb2021-12-23 12:41:25 -0800111// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000114constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000116const ui::Transform kIdentityTransform;
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119 return systemTime(SYSTEM_TIME_MONOTONIC);
120}
121
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700122inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000123 if (binder == nullptr) {
124 return "<null>";
125 }
126 return StringPrintf("%p", binder.get());
127}
128
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000129static std::string uidString(const gui::Uid& uid) {
130 return uid.toString();
131}
132
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
135 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136}
137
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700138Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AKEY_EVENT_ACTION_DOWN:
141 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700142 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700144 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 }
146}
147
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700148Result<void> validateKeyEvent(int32_t action) {
149 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150}
151
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700152Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800153 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700155 case AMOTION_EVENT_ACTION_UP: {
156 if (pointerCount != 1) {
157 return Error() << "invalid pointer count " << pointerCount;
158 }
159 return {};
160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_HOVER_ENTER:
163 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700164 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
165 if (pointerCount < 1) {
166 return Error() << "invalid pointer count " << pointerCount;
167 }
168 return {};
169 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700173 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800176 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700177 if (index < 0) {
178 return Error() << "invalid index " << index << " for "
179 << MotionEvent::actionToString(action);
180 }
181 if (index >= pointerCount) {
182 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
183 }
184 if (pointerCount <= 1) {
185 return Error() << "invalid pointer count " << pointerCount << " for "
186 << MotionEvent::actionToString(action);
187 }
188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 }
190 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700191 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
192 if (actionButton == 0) {
193 return Error() << "action button should be nonzero for "
194 << MotionEvent::actionToString(action);
195 }
196 return {};
197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 default:
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700199 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
201}
202
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000203int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
205}
206
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700207Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
208 const PointerProperties* pointerProperties) {
209 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
210 if (!actionCheck.ok()) {
211 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700214 return Error() << "Motion event has invalid pointer count " << pointerCount
215 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800217 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700221 return Error() << "Motion event has invalid pointer id " << id
222 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800224 if (pointerIdBits.test(id)) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700225 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800227 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou6773db62023-04-21 11:30:20 -0700229 return {};
230}
231
232Result<void> validateInputEvent(const InputEvent& event) {
233 switch (event.getType()) {
234 case InputEventType::KEY: {
235 const KeyEvent& key = static_cast<const KeyEvent&>(event);
236 const int32_t action = key.getAction();
237 return validateKeyEvent(action);
238 }
239 case InputEventType::MOTION: {
240 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
241 const int32_t action = motion.getAction();
242 const size_t pointerCount = motion.getPointerCount();
243 const PointerProperties* pointerProperties = motion.getPointerProperties();
244 const int32_t actionButton = motion.getActionButton();
245 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
246 }
247 default: {
248 return {};
249 }
250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500275 constexpr size_t maxEntries = 50; // max events to print
276 constexpr size_t skipBegin = maxEntries / 2;
277 const size_t skipEnd = queue.size() - maxEntries / 2;
278 // skip from maxEntries / 2 ... size() - maxEntries/2
279 // only print from 0 .. skipBegin and then from skipEnd .. size()
280
281 std::string dump;
282 for (size_t i = 0; i < queue.size(); i++) {
283 const DispatchEntry& entry = *queue[i];
284 if (i >= skipBegin && i < skipEnd) {
285 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
286 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
287 continue;
288 }
289 dump.append(INDENT4);
290 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800291 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
292 "ms",
293 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500294 ns2ms(currentTime - entry.eventEntry->eventTime));
295 if (entry.deliveryTime != 0) {
296 // This entry was delivered, so add information on how long we've been waiting
297 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
298 }
299 dump.append("\n");
300 }
301 return dump;
302}
303
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700304/**
305 * Find the entry in std::unordered_map by key, and return it.
306 * If the entry is not found, return a default constructed entry.
307 *
308 * Useful when the entries are vectors, since an empty vector will be returned
309 * if the entry is not found.
310 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
311 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700312template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700314 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800316}
317
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700319 if (first == second) {
320 return true;
321 }
322
323 if (first == nullptr || second == nullptr) {
324 return false;
325 }
326
327 return first->getToken() == second->getToken();
328}
329
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000330bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000331 if (first == nullptr || second == nullptr) {
332 return false;
333 }
334 return first->applicationInfo.token != nullptr &&
335 first->applicationInfo.token == second->applicationInfo.token;
336}
337
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800338template <typename T>
339size_t firstMarkedBit(T set) {
340 // TODO: replace with std::countr_zero from <bit> when that's available
341 LOG_ALWAYS_FATAL_IF(set.none());
342 size_t i = 0;
343 while (!set.test(i)) {
344 i++;
345 }
346 return i;
347}
348
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800349std::unique_ptr<DispatchEntry> createDispatchEntry(
350 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
351 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700352 if (inputTarget.useDefaultPointerTransform()) {
353 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700354 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700355 inputTarget.displayTransform,
356 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357 }
358
359 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
360 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
361
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700362 std::vector<PointerCoords> pointerCoords;
363 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364
365 // Use the first pointer information to normalize all other pointers. This could be any pointer
366 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 // uses the transform for the normalized pointer.
368 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800369 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371
372 // Iterate through all pointers in the event to normalize against the first.
373 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
374 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
375 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700376 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000377
378 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 // First, apply the current pointer's transform to update the coordinates into
380 // window space.
381 pointerCoords[pointerIndex].transform(currTransform);
382 // Next, apply the inverse transform of the normalized coordinates so the
383 // current coordinates are transformed into the normalized coordinate space.
384 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000385 }
386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700387 std::unique_ptr<MotionEntry> combinedMotionEntry =
388 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
389 motionEntry.deviceId, motionEntry.source,
390 motionEntry.displayId, motionEntry.policyFlags,
391 motionEntry.action, motionEntry.actionButton,
392 motionEntry.flags, motionEntry.metaState,
393 motionEntry.buttonState, motionEntry.classification,
394 motionEntry.edgeFlags, motionEntry.xPrecision,
395 motionEntry.yPrecision, motionEntry.xCursorPosition,
396 motionEntry.yCursorPosition, motionEntry.downTime,
397 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000398 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399
400 if (motionEntry.injectionState) {
401 combinedMotionEntry->injectionState = motionEntry.injectionState;
402 combinedMotionEntry->injectionState->refCount += 1;
403 }
404
405 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700406 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700407 firstPointerTransform, inputTarget.displayTransform,
408 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000409 return dispatchEntry;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
413 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700414 std::unique_ptr<InputChannel> uniqueServerChannel;
415 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
416
417 serverChannel = std::move(uniqueServerChannel);
418 return result;
419}
420
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500421template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000422bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500423 if (lhs == nullptr && rhs == nullptr) {
424 return true;
425 }
426 if (lhs == nullptr || rhs == nullptr) {
427 return false;
428 }
429 return *lhs == *rhs;
430}
431
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000432KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000433 KeyEvent event;
434 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
435 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
436 entry.repeatCount, entry.downTime, entry.eventTime);
437 return event;
438}
439
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000440bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000441 // Do not keep track of gesture monitors. They receive every event and would disproportionately
442 // affect the statistics.
443 if (connection.monitor) {
444 return false;
445 }
446 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
447 if (!connection.responsive) {
448 return false;
449 }
450 return true;
451}
452
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000453bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
455 const int32_t& inputEventId = eventEntry.id;
456 if (inputEventId != dispatchEntry.resolvedEventId) {
457 // Event was transmuted
458 return false;
459 }
460 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
461 return false;
462 }
463 // Only track latency for events that originated from hardware
464 if (eventEntry.isSynthesized()) {
465 return false;
466 }
467 const EventEntry::Type& inputEventEntryType = eventEntry.type;
468 if (inputEventEntryType == EventEntry::Type::KEY) {
469 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
470 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
471 return false;
472 }
473 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
474 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
475 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
476 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
477 return false;
478 }
479 } else {
480 // Not a key or a motion
481 return false;
482 }
483 if (!shouldReportMetricsForConnection(connection)) {
484 return false;
485 }
486 return true;
487}
488
Prabir Pradhancef936d2021-07-21 16:17:52 +0000489/**
490 * Connection is responsive if it has no events in the waitQueue that are older than the
491 * current time.
492 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000493bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000494 const nsecs_t currentTime = now();
495 for (const DispatchEntry* entry : connection.waitQueue) {
496 if (entry->timeoutTime < currentTime) {
497 return false;
498 }
499 }
500 return true;
501}
502
Antonio Kantekf16f2832021-09-28 04:39:20 +0000503// Returns true if the event type passed as argument represents a user activity.
504bool isUserActivityEvent(const EventEntry& eventEntry) {
505 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000506 case EventEntry::Type::CONFIGURATION_CHANGED:
507 case EventEntry::Type::DEVICE_RESET:
508 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000509 case EventEntry::Type::FOCUS:
510 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000511 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000512 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 case EventEntry::Type::KEY:
515 case EventEntry::Type::MOTION:
516 return true;
517 }
518}
519
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800520// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000521bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000522 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800523 const auto inputConfig = windowInfo.inputConfig;
524 if (windowInfo.displayId != displayId ||
525 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800526 return false;
527 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700528 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800529 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000532
533 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
534 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
535 // the window. Points on the right and bottom edges should not be inside the window, so we need
536 // to be careful about performing a hit test when the display is rotated, since the "right" and
537 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
538 // logical display in which WM determined the bounds. Perform the hit test in the logical
539 // display space to ensure these edges are considered correctly in all orientations.
540 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
541 const auto p = displayTransform.transform(x, y);
542 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800543 return false;
544 }
545 return true;
546}
547
Prabir Pradhand65552b2021-10-07 11:23:50 -0700548bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
549 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000550 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551}
552
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800553// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000554// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
555// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
556// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558bool canReceiveForegroundTouches(const WindowInfo& info) {
559 // A non-touchable window can still receive touch events (e.g. in the case of
560 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
561 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
562}
563
Prabir Pradhane59c6dc2023-06-13 19:53:03 +0000564bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700565 if (windowHandle == nullptr) {
566 return false;
567 }
568 const WindowInfo* windowInfo = windowHandle->getInfo();
569 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
570 return true;
571 }
572 return false;
573}
574
Prabir Pradhan5735a322022-04-11 17:23:34 +0000575// Checks targeted injection using the window's owner's uid.
576// Returns an empty string if an entry can be sent to the given window, or an error message if the
577// entry is a targeted injection whose uid target doesn't match the window owner.
578std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
579 const EventEntry& entry) {
580 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
581 // The event was not injected, or the injected event does not target a window.
582 return {};
583 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000584 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000585 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000586 return StringPrintf("No valid window target for injection into uid %s.",
587 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 }
589 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
591 "owned by uid %s.",
592 uid.toString().c_str(), window->getName().c_str(),
593 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000594 }
595 return {};
596}
597
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000598std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700599 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
600 // Always dispatch mouse events to cursor position.
601 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 }
604
605 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
607 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700608}
609
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700610std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
611 if (eventEntry.type == EventEntry::Type::KEY) {
612 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
613 return keyEntry.downTime;
614 } else if (eventEntry.type == EventEntry::Type::MOTION) {
615 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
616 return motionEntry.downTime;
617 }
618 return std::nullopt;
619}
620
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000621/**
622 * Compare the old touch state to the new touch state, and generate the corresponding touched
623 * windows (== input targets).
624 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
625 * If the pointer just entered the new window, produce HOVER_ENTER.
626 * For pointers remaining in the window, produce HOVER_MOVE.
627 */
628std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
629 const TouchState& newTouchState,
630 const MotionEntry& entry) {
631 std::vector<TouchedWindow> out;
632 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
633 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
634 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
635 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
636 // Not a hover event - don't need to do anything
637 return out;
638 }
639
640 // We should consider all hovering pointers here. But for now, just use the first one
641 const int32_t pointerId = entry.pointerProperties[0].id;
642
643 std::set<sp<WindowInfoHandle>> oldWindows;
644 if (oldState != nullptr) {
645 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
646 }
647
648 std::set<sp<WindowInfoHandle>> newWindows =
649 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
650
651 // If the pointer is no longer in the new window set, send HOVER_EXIT.
652 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
653 if (newWindows.find(oldWindow) == newWindows.end()) {
654 TouchedWindow touchedWindow;
655 touchedWindow.windowHandle = oldWindow;
656 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000657 out.push_back(touchedWindow);
658 }
659 }
660
661 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
662 TouchedWindow touchedWindow;
663 touchedWindow.windowHandle = newWindow;
664 if (oldWindows.find(newWindow) == oldWindows.end()) {
665 // Any windows that have this pointer now, and didn't have it before, should get
666 // HOVER_ENTER
667 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
668 } else {
669 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700670 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman2f99cdb2023-08-02 16:39:45 -0700671 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
672 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
673 // The Accessibility injected touch exploration event stream
674 // has known inconsistencies, so log ERROR instead of
675 // crashing the device with FATAL.
676 // TODO(b/286037469): Move a11y severity back to FATAL.
677 severity = android::base::LogSeverity::ERROR;
678 }
679 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700680 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000681 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
682 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700683 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
685 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
686 }
687 out.push_back(touchedWindow);
688 }
689 return out;
690}
691
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800692template <typename T>
693std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
694 left.insert(left.end(), right.begin(), right.end());
695 return left;
696}
697
Harry Cuttsb166c002023-05-09 13:06:05 +0000698// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
699// both.
700void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
701 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
702 if (!window.windowHandle->getInfo()->inputConfig.test(
703 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
704 // In addition to TouchState, erase this window from the input targets! We don't have a
705 // good way to do this today except by adding a nested loop.
706 // TODO(b/282025641): simplify this code once InputTargets are being identified
707 // separately from TouchedWindows.
708 std::erase_if(targets, [&](const InputTarget& target) {
709 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
710 });
711 return true;
712 }
713 return false;
714 });
715}
716
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000717} // namespace
718
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719// --- InputDispatcher ---
720
Prabir Pradhana41d2442023-04-20 21:30:40 +0000721InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800722 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
723
Prabir Pradhana41d2442023-04-20 21:30:40 +0000724InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800725 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700726 : mPolicy(policy),
727 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700728 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800729 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700730 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700731 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700732 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800733 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700734 mDispatchEnabled(false),
735 mDispatchFrozen(false),
736 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100737 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000738 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800739 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800740 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000741 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000742 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700743 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800744 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700746 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700747#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700748 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700749#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700750 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751}
752
753InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000754 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755
Prabir Pradhancef936d2021-07-21 16:17:52 +0000756 resetKeyRepeatLocked();
757 releasePendingEventLocked();
758 drainInboundQueueLocked();
759 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000761 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700762 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000763 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 }
765}
766
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700767status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700768 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700769 return ALREADY_EXISTS;
770 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700771 mThread = std::make_unique<InputThread>(
772 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
773 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700774}
775
776status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700777 if (mThread && mThread->isCallingThread()) {
778 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700779 return INVALID_OPERATION;
780 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700781 mThread.reset();
782 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700783}
784
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700786 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800788 std::scoped_lock _l(mLock);
789 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790
791 // Run a dispatch loop if there are no pending commands.
792 // The dispatch loop might enqueue commands to run afterwards.
793 if (!haveCommandsLocked()) {
794 dispatchOnceInnerLocked(&nextWakeupTime);
795 }
796
797 // Run all pending commands if there are any.
798 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000799 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700800 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800802
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700803 // If we are still waiting for ack on some events,
804 // we might have to wake up earlier to check if an app is anr'ing.
805 const nsecs_t nextAnrCheck = processAnrsLocked();
806 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
807
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800808 // We are about to enter an infinitely long sleep, because we have no commands or
809 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700810 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800811 mDispatcherEnteredIdle.notify_all();
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 } // release lock
814
815 // Wait for callback or timeout or wake. (make sure we round up, not down)
816 nsecs_t currentTime = now();
817 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
818 mLooper->pollOnce(timeoutMillis);
819}
820
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700821/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500822 * Raise ANR if there is no focused window.
823 * Before the ANR is raised, do a final state check:
824 * 1. The currently focused application must be the same one we are waiting for.
825 * 2. Ensure we still don't have a focused window.
826 */
827void InputDispatcher::processNoFocusedWindowAnrLocked() {
828 // Check if the application that we are waiting for is still focused.
829 std::shared_ptr<InputApplicationHandle> focusedApplication =
830 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
831 if (focusedApplication == nullptr ||
832 focusedApplication->getApplicationToken() !=
833 mAwaitedFocusedApplication->getApplicationToken()) {
834 // Unexpected because we should have reset the ANR timer when focused application changed
835 ALOGE("Waited for a focused window, but focused application has already changed to %s",
836 focusedApplication->getName().c_str());
837 return; // The focused application has changed.
838 }
839
chaviw98318de2021-05-19 16:45:23 -0500840 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500841 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
842 if (focusedWindowHandle != nullptr) {
843 return; // We now have a focused window. No need for ANR.
844 }
845 onAnrLocked(mAwaitedFocusedApplication);
846}
847
848/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700849 * Check if any of the connections' wait queues have events that are too old.
850 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
851 * Return the time at which we should wake up next.
852 */
853nsecs_t InputDispatcher::processAnrsLocked() {
854 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700855 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
857 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
858 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500859 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700860 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500861 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700862 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700863 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500864 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700865 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
866 }
867 }
868
869 // Check if any connection ANRs are due
870 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
871 if (currentTime < nextAnrCheck) { // most likely scenario
872 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
873 }
874
875 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700876 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700877 if (connection == nullptr) {
878 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
879 return nextAnrCheck;
880 }
881 connection->responsive = false;
882 // Stop waking up for this unresponsive connection
883 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000884 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700885 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886}
887
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800888std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700889 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800890 if (connection->monitor) {
891 return mMonitorDispatchingTimeout;
892 }
893 const sp<WindowInfoHandle> window =
894 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500896 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700897 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500898 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899}
900
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
902 nsecs_t currentTime = now();
903
Jeff Browndc5992e2014-04-11 01:27:26 -0700904 // Reset the key repeat timer whenever normal dispatch is suspended while the
905 // device is in a non-interactive state. This is to ensure that we abort a key
906 // repeat if the device is just coming out of sleep.
907 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 resetKeyRepeatLocked();
909 }
910
911 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
912 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100913 if (DEBUG_FOCUS) {
914 ALOGD("Dispatch frozen. Waiting some more.");
915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 return;
917 }
918
919 // Optimize latency of app switches.
920 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
921 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
922 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
923 if (mAppSwitchDueTime < *nextWakeupTime) {
924 *nextWakeupTime = mAppSwitchDueTime;
925 }
926
927 // Ready to start a new event.
928 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700930 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 if (isAppSwitchDue) {
932 // The inbound queue is empty so the app switch key we were waiting
933 // for will never arrive. Stop waiting for it.
934 resetPendingAppSwitchLocked(false);
935 isAppSwitchDue = false;
936 }
937
938 // Synthesize a key repeat if appropriate.
939 if (mKeyRepeatState.lastKeyEntry) {
940 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
941 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
942 } else {
943 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
944 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
945 }
946 }
947 }
948
949 // Nothing to do if there is no pending event.
950 if (!mPendingEvent) {
951 return;
952 }
953 } else {
954 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700955 mPendingEvent = mInboundQueue.front();
956 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 traceInboundQueueLengthLocked();
958 }
959
960 // Poke user activity for this event.
961 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700962 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
965
966 // Now we have an event to dispatch.
967 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700968 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700970 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700974 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 }
976
977 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700978 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980
981 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 const ConfigurationChangedEntry& typedEntry =
984 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700986 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 break;
988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700990 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 const DeviceResetEntry& typedEntry =
992 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700994 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 break;
996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100998 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999 std::shared_ptr<FocusEntry> typedEntry =
1000 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001 dispatchFocusLocked(currentTime, typedEntry);
1002 done = true;
1003 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1004 break;
1005 }
1006
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001007 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1008 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1009 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1010 done = true;
1011 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1012 break;
1013 }
1014
Prabir Pradhan99987712020-11-10 18:43:05 -08001015 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1016 const auto typedEntry =
1017 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1018 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1019 done = true;
1020 break;
1021 }
1022
arthurhungb89ccb02020-12-30 16:19:01 +08001023 case EventEntry::Type::DRAG: {
1024 std::shared_ptr<DragEntry> typedEntry =
1025 std::static_pointer_cast<DragEntry>(mPendingEvent);
1026 dispatchDragLocked(currentTime, typedEntry);
1027 done = true;
1028 break;
1029 }
1030
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001031 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001032 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 resetPendingAppSwitchLocked(true);
1036 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001037 } else if (dropReason == DropReason::NOT_DROPPED) {
1038 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 }
1040 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001041 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001042 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001044 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1045 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001047 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048 break;
1049 }
1050
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001051 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001052 std::shared_ptr<MotionEntry> motionEntry =
1053 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001054 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1055 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001057 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001058 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001060 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1061 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001063 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
Chris Yef59a2f42020-10-16 12:55:26 -07001066
1067 case EventEntry::Type::SENSOR: {
1068 std::shared_ptr<SensorEntry> sensorEntry =
1069 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1070 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1071 dropReason = DropReason::APP_SWITCH;
1072 }
1073 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1074 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1075 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1076 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1077 dropReason = DropReason::STALE;
1078 }
1079 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1080 done = true;
1081 break;
1082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 }
1084
1085 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001087 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
Michael Wright3a981722015-06-10 15:26:13 +01001089 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
1091 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001092 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
1094}
1095
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001096bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1097 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1098}
1099
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001100/**
1101 * Return true if the events preceding this incoming motion event should be dropped
1102 * Return false otherwise (the default behaviour)
1103 */
1104bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001105 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001106 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001107
1108 // Optimize case where the current application is unresponsive and the user
1109 // decides to touch a window in a different application.
1110 // If the application takes too long to catch up then we drop all events preceding
1111 // the touch into the other window.
1112 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001113 const int32_t displayId = motionEntry.displayId;
1114 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001115 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001116
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001117 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001118 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001119 touchedWindowHandle->getApplicationToken() !=
1120 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001121 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001122 ALOGI("Pruning input queue because user touched a different application while waiting "
1123 "for %s",
1124 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001125 return true;
1126 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001127
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001128 // Alternatively, maybe there's a spy window that could handle this event.
1129 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1130 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1131 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001132 const std::shared_ptr<Connection> connection =
1133 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001134 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001135 // This spy window could take more input. Drop all events preceding this
1136 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001137 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001138 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001139 mAwaitedFocusedApplication->getName().c_str());
1140 return true;
1141 }
1142 }
1143 }
1144
1145 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1146 // yet been processed by some connections, the dispatcher will wait for these motion
1147 // events to be processed before dispatching the key event. This is because these motion events
1148 // may cause a new window to be launched, which the user might expect to receive focus.
1149 // To prevent waiting forever for such events, just send the key to the currently focused window
1150 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1151 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1152 "just send the pending key event to the focused window.");
1153 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001154 }
1155 return false;
1156}
1157
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001158bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001159 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 mInboundQueue.push_back(std::move(newEntry));
1161 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 traceInboundQueueLengthLocked();
1163
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001164 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001165 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001166 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1167 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 // Optimize app switch latency.
1169 // If the application takes too long to catch up then we drop all events preceding
1170 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001171 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001174 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001175 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001177 if (DEBUG_APP_SWITCH) {
1178 ALOGD("App switch is pending!");
1179 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001180 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 mAppSwitchSawKeyDown = false;
1182 needWake = true;
1183 }
1184 }
1185 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001186
1187 // If a new up event comes in, and the pending event with same key code has been asked
1188 // to try again later because of the policy. We have to reset the intercept key wake up
1189 // time for it may have been handled in the policy and could be dropped.
1190 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1191 mPendingEvent->type == EventEntry::Type::KEY) {
1192 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1193 if (pendingKey.keyCode == keyEntry.keyCode &&
1194 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001195 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1196 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001197 pendingKey.interceptKeyWakeupTime = 0;
1198 needWake = true;
1199 }
1200 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 break;
1202 }
1203
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001204 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001205 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1206 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1208 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001209 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001213 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001214 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1215 break;
1216 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001217 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001218 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001219 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001220 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001221 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1222 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001223 // nothing to do
1224 break;
1225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227
1228 return needWake;
1229}
1230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001232 // Do not store sensor event in recent queue to avoid flooding the queue.
1233 if (entry->type != EventEntry::Type::SENSOR) {
1234 mRecentQueue.push_back(entry);
1235 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001237 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 }
1239}
1240
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001241std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001242InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001243 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001245 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001246 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001247 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001248 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001249 continue;
1250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001252 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001253 if (!info.isSpy() &&
1254 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001255 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001256 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001257
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001258 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1259 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001260 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001261 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001264 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265}
1266
Prabir Pradhand65552b2021-10-07 11:23:50 -07001267std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001268 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001269 // Traverse windows from front to back and gather the touched spy windows.
1270 std::vector<sp<WindowInfoHandle>> spyWindows;
1271 const auto& windowHandles = getWindowHandlesLocked(displayId);
1272 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1273 const WindowInfo& info = *windowHandle->getInfo();
1274
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001275 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001276 continue;
1277 }
1278 if (!info.isSpy()) {
1279 // The first touched non-spy window was found, so return the spy windows touched so far.
1280 return spyWindows;
1281 }
1282 spyWindows.push_back(windowHandle);
1283 }
1284 return spyWindows;
1285}
1286
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 const char* reason;
1289 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001290 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001291 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001292 ALOGD("Dropped event because policy consumed it.");
1293 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 reason = "inbound event was dropped because the policy consumed it";
1295 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001296 case DropReason::DISABLED:
1297 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 ALOGI("Dropped event because input dispatch is disabled.");
1299 }
1300 reason = "inbound event was dropped because input dispatch is disabled";
1301 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001302 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 ALOGI("Dropped event because of pending overdue app switch.");
1304 reason = "inbound event was dropped because of pending overdue app switch";
1305 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001306 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 ALOGI("Dropped event because the current application is not responding and the user "
1308 "has started interacting with a different application.");
1309 reason = "inbound event was dropped because the current application is not responding "
1310 "and the user has started interacting with a different application";
1311 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001312 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 ALOGI("Dropped event because it is stale.");
1314 reason = "inbound event was dropped because it is stale";
1315 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 case DropReason::NO_POINTER_CAPTURE:
1317 ALOGI("Dropped event because there is no window with Pointer Capture.");
1318 reason = "inbound event was dropped because there is no window with Pointer Capture";
1319 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001320 case DropReason::NOT_DROPPED: {
1321 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 }
1325
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001327 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001328 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001332 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001333 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1334 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001335 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 synthesizeCancelationEventsForAllConnectionsLocked(options);
1337 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001338 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1339 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001340 synthesizeCancelationEventsForAllConnectionsLocked(options);
1341 }
1342 break;
1343 }
Chris Yef59a2f42020-10-16 12:55:26 -07001344 case EventEntry::Type::SENSOR: {
1345 break;
1346 }
arthurhungb89ccb02020-12-30 16:19:01 +08001347 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1348 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 break;
1350 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001351 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001352 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001353 case EventEntry::Type::CONFIGURATION_CHANGED:
1354 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001355 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001356 break;
1357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359}
1360
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001361static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001362 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1363 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364}
1365
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001366bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1367 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1368 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1369 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001372bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001373 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374}
1375
1376void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001377 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001379 if (DEBUG_APP_SWITCH) {
1380 if (handled) {
1381 ALOGD("App switch has arrived.");
1382 } else {
1383 ALOGD("App switch was abandoned.");
1384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386}
1387
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001389 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390}
1391
Prabir Pradhancef936d2021-07-21 16:17:52 +00001392bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001393 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return false;
1395 }
1396
1397 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001398 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001399 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001400 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1401 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001402 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 return true;
1404}
1405
Prabir Pradhancef936d2021-07-21 16:17:52 +00001406void InputDispatcher::postCommandLocked(Command&& command) {
1407 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408}
1409
1410void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001411 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001412 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001413 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 releaseInboundEventLocked(entry);
1415 }
1416 traceInboundQueueLengthLocked();
1417}
1418
1419void InputDispatcher::releasePendingEventLocked() {
1420 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001422 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424}
1425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001429 if (DEBUG_DISPATCH_CYCLE) {
1430 ALOGD("Injected inbound event was dropped.");
1431 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001432 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 }
1434 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 }
1437 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438}
1439
1440void InputDispatcher::resetKeyRepeatLocked() {
1441 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001442 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
1444}
1445
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1447 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
Michael Wright2e732952014-09-24 13:26:59 -07001449 uint32_t policyFlags = entry->policyFlags &
1450 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 std::shared_ptr<KeyEntry> newEntry =
1453 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1454 entry->source, entry->displayId, policyFlags, entry->action,
1455 entry->flags, entry->keyCode, entry->scanCode,
1456 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001458 newEntry->syntheticRepeat = true;
1459 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001461 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462}
1463
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001466 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1467 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469
1470 // Reset key repeating in case a keyboard device was added or removed or something.
1471 resetKeyRepeatLocked();
1472
1473 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001474 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1475 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001476 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001477 };
1478 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 return true;
1480}
1481
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1483 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001484 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1485 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1486 entry.deviceId);
1487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488
liushenxiang42232912021-05-21 20:24:09 +08001489 // Reset key repeating in case a keyboard device was disabled or enabled.
1490 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1491 resetKeyRepeatLocked();
1492 }
1493
Michael Wrightfb04fd52022-11-24 22:31:11 +00001494 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001495 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001497
1498 // Remove all active pointers from this device
1499 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1500 touchState.removeAllPointersForDevice(entry.deviceId);
1501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 return true;
1503}
1504
Vishnu Nairad321cd2020-08-20 16:40:21 -07001505void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001506 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001507 if (mPendingEvent != nullptr) {
1508 // Move the pending event to the front of the queue. This will give the chance
1509 // for the pending event to get dispatched to the newly focused window
1510 mInboundQueue.push_front(mPendingEvent);
1511 mPendingEvent = nullptr;
1512 }
1513
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001514 std::unique_ptr<FocusEntry> focusEntry =
1515 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1516 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001517
1518 // This event should go to the front of the queue, but behind all other focus events
1519 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001521 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 [](const std::shared_ptr<EventEntry>& event) {
1523 return event->type == EventEntry::Type::FOCUS;
1524 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001525
1526 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001528}
1529
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001530void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001531 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001532 if (channel == nullptr) {
1533 return; // Window has gone away
1534 }
1535 InputTarget target;
1536 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001537 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001538 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001539 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1540 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001541 std::string reason = std::string("reason=").append(entry->reason);
1542 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001543 dispatchEventLocked(currentTime, entry, {target});
1544}
1545
Prabir Pradhan99987712020-11-10 18:43:05 -08001546void InputDispatcher::dispatchPointerCaptureChangedLocked(
1547 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1548 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001549 dropReason = DropReason::NOT_DROPPED;
1550
Prabir Pradhan99987712020-11-10 18:43:05 -08001551 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001552 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553
1554 if (entry->pointerCaptureRequest.enable) {
1555 // Enable Pointer Capture.
1556 if (haveWindowWithPointerCapture &&
1557 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001558 // This can happen if pointer capture is disabled and re-enabled before we notify the
1559 // app of the state change, so there is no need to notify the app.
1560 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1561 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001562 }
1563 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001564 // This can happen if a window requests capture and immediately releases capture.
1565 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001566 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001567 return;
1568 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001569 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1570 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1571 return;
1572 }
1573
Vishnu Nairc519ff72021-01-21 08:23:08 -08001574 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001575 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1576 mWindowTokenWithPointerCapture = token;
1577 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001578 // Disable Pointer Capture.
1579 // We do not check if the sequence number matches for requests to disable Pointer Capture
1580 // for two reasons:
1581 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1582 // to disable capture with the same sequence number: one generated by
1583 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1584 // Capture being disabled in InputReader.
1585 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1586 // actual Pointer Capture state that affects events being generated by input devices is
1587 // in InputReader.
1588 if (!haveWindowWithPointerCapture) {
1589 // Pointer capture was already forcefully disabled because of focus change.
1590 dropReason = DropReason::NOT_DROPPED;
1591 return;
1592 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001593 token = mWindowTokenWithPointerCapture;
1594 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001595 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001596 setPointerCaptureLocked(false);
1597 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001598 }
1599
1600 auto channel = getInputChannelLocked(token);
1601 if (channel == nullptr) {
1602 // Window has gone away, clean up Pointer Capture state.
1603 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001604 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001605 setPointerCaptureLocked(false);
1606 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001607 return;
1608 }
1609 InputTarget target;
1610 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001611 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001612 entry->dispatchInProgress = true;
1613 dispatchEventLocked(currentTime, entry, {target});
1614
1615 dropReason = DropReason::NOT_DROPPED;
1616}
1617
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001618void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1619 const std::shared_ptr<TouchModeEntry>& entry) {
1620 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001621 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001622 if (windowHandles.empty()) {
1623 return;
1624 }
1625 const std::vector<InputTarget> inputTargets =
1626 getInputTargetsFromWindowHandlesLocked(windowHandles);
1627 if (inputTargets.empty()) {
1628 return;
1629 }
1630 entry->dispatchInProgress = true;
1631 dispatchEventLocked(currentTime, entry, inputTargets);
1632}
1633
1634std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1635 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1636 std::vector<InputTarget> inputTargets;
1637 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001638 const sp<IBinder>& token = handle->getToken();
1639 if (token == nullptr) {
1640 continue;
1641 }
1642 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1643 if (channel == nullptr) {
1644 continue; // Window has gone away
1645 }
1646 InputTarget target;
1647 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001648 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001649 inputTargets.push_back(target);
1650 }
1651 return inputTargets;
1652}
1653
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001654bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 if (!entry->dispatchInProgress) {
1658 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1659 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1660 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1661 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001662 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 // We have seen two identical key downs in a row which indicates that the device
1664 // driver is automatically generating key repeats itself. We take note of the
1665 // repeat here, but we disable our own next key repeat timer since it is clear that
1666 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001667 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1668 // Make sure we don't get key down from a different device. If a different
1669 // device Id has same key pressed down, the new device Id will replace the
1670 // current one to hold the key repeat with repeat count reset.
1671 // In the future when got a KEY_UP on the device id, drop it and do not
1672 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1674 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001675 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 } else {
1677 // Not a repeat. Save key down state in case we do see a repeat later.
1678 resetKeyRepeatLocked();
1679 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1680 }
1681 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001682 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1683 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001685 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001686 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1687 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001688 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 resetKeyRepeatLocked();
1690 }
1691
1692 if (entry->repeatCount == 1) {
1693 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1694 } else {
1695 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1696 }
1697
1698 entry->dispatchInProgress = true;
1699
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001700 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702
1703 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001704 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 if (currentTime < entry->interceptKeyWakeupTime) {
1706 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1707 *nextWakeupTime = entry->interceptKeyWakeupTime;
1708 }
1709 return false; // wait until next wakeup
1710 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001711 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 entry->interceptKeyWakeupTime = 0;
1713 }
1714
1715 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001716 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001718 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001719 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001720
1721 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1722 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1723 };
1724 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001725 // Poke user activity for keys not passed to user
1726 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 return false; // wait for the command to run
1728 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001729 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001731 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001732 if (*dropReason == DropReason::NOT_DROPPED) {
1733 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735 }
1736
1737 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001738 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1741 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001742 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001743 // Poke user activity for undispatched keys
1744 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 return true;
1746 }
1747
1748 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001749 InputEventInjectionResult injectionResult;
1750 sp<WindowInfoHandle> focusedWindow =
1751 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1752 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001753 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 return false;
1755 }
1756
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001757 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001758 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 return true;
1760 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001761 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1762
1763 std::vector<InputTarget> inputTargets;
1764 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001765 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001766 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001768 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001769 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770
1771 // Dispatch the key.
1772 dispatchEventLocked(currentTime, entry, inputTargets);
1773 return true;
1774}
1775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001776void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001777 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1778 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1779 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1780 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1781 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1782 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1783 entry.metaState, entry.repeatCount, entry.downTime);
1784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785}
1786
Prabir Pradhancef936d2021-07-21 16:17:52 +00001787void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1788 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001789 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001790 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1791 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1792 "source=0x%x, sensorType=%s",
1793 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001794 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001795 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001796 auto command = [this, entry]() REQUIRES(mLock) {
1797 scoped_unlock unlock(mLock);
1798
1799 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001800 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001801 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001802 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1803 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001804 };
1805 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001806}
1807
1808bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001809 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1810 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001811 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001812 }
Chris Yef59a2f42020-10-16 12:55:26 -07001813 { // acquire lock
1814 std::scoped_lock _l(mLock);
1815
1816 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1817 std::shared_ptr<EventEntry> entry = *it;
1818 if (entry->type == EventEntry::Type::SENSOR) {
1819 it = mInboundQueue.erase(it);
1820 releaseInboundEventLocked(entry);
1821 }
1822 }
1823 }
1824 return true;
1825}
1826
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001827bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001828 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001829 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001831 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 entry->dispatchInProgress = true;
1833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 }
1836
1837 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001838 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001839 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001840 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1841 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 return true;
1843 }
1844
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001845 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
1847 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001848 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849
1850 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 if (isPointerEvent) {
1853 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001854
1855 if (mDragState &&
1856 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1857 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1858 pilferPointersLocked(mDragState->dragWindow->getToken());
1859 }
1860
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001861 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001862 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001863 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001864 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1865 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 } else {
1867 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001868 sp<WindowInfoHandle> focusedWindow =
1869 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1870 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1871 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1872 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001873 InputTarget::Flags::FOREGROUND |
1874 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001875 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 return false;
1880 }
1881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001882 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001883 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001884 return true;
1885 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001887 CancelationOptions::Mode mode(
1888 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1889 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001890 CancelationOptions options(mode, "input event injection failed");
1891 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 return true;
1893 }
1894
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001895 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001896 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897
1898 // Dispatch the motion.
1899 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001900 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001901 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 synthesizeCancelationEventsForAllConnectionsLocked(options);
1903 }
1904 dispatchEventLocked(currentTime, entry, inputTargets);
1905 return true;
1906}
1907
chaviw98318de2021-05-19 16:45:23 -05001908void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001909 bool isExiting, const int32_t rawX,
1910 const int32_t rawY) {
1911 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001912 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001913 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1914 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001915
1916 enqueueInboundEventLocked(std::move(dragEntry));
1917}
1918
1919void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1920 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1921 if (channel == nullptr) {
1922 return; // Window has gone away
1923 }
1924 InputTarget target;
1925 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001926 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001927 entry->dispatchInProgress = true;
1928 dispatchEventLocked(currentTime, entry, {target});
1929}
1930
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001932 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001933 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001934 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001935 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001936 "metaState=0x%x, buttonState=0x%x,"
1937 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001938 prefix, entry.eventTime, entry.deviceId,
1939 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1940 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1941 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1942 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001944 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001945 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001946 "x=%f, y=%f, pressure=%f, size=%f, "
1947 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1948 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001949 i, entry.pointerProperties[i].id,
1950 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001951 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1952 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1953 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1954 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1955 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1956 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1957 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1958 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1959 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962}
1963
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001964void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1965 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001966 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001967 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001968 if (DEBUG_DISPATCH_CYCLE) {
1969 ALOGD("dispatchEventToCurrentInputTargets");
1970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00001972 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001973
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1975
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001976 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001978 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001979 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001980 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001981 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001982 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001984 if (DEBUG_FOCUS) {
1985 ALOGD("Dropping event delivery to target with channel '%s' because it "
1986 "is no longer registered with the input dispatcher.",
1987 inputTarget.inputChannel->getName().c_str());
1988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
1990 }
1991}
1992
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001993void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1995 // If the policy decides to close the app, we will get a channel removal event via
1996 // unregisterInputChannel, and will clean up the connection that way. We are already not
1997 // sending new pointers to the connection when it blocked, but focused events will continue to
1998 // pile up.
1999 ALOGW("Canceling events for %s because it is unresponsive",
2000 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002001 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002002 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002003 "application not responding");
2004 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 }
2006}
2007
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002008void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002009 if (DEBUG_FOCUS) {
2010 ALOGD("Resetting ANR timeouts.");
2011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012
2013 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002015 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016}
2017
Tiger Huang721e26f2018-07-24 22:26:19 +08002018/**
2019 * Get the display id that the given event should go to. If this event specifies a valid display id,
2020 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2021 * Focused display is the display that the user most recently interacted with.
2022 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002024 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002025 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002026 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002027 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2028 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 break;
2030 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002031 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2033 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002034 break;
2035 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002036 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002037 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002038 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002039 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002040 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002041 case EventEntry::Type::SENSOR:
2042 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002043 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 return ADISPLAY_ID_NONE;
2045 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002046 }
2047 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2048}
2049
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2051 const char* focusedWindowName) {
2052 if (mAnrTracker.empty()) {
2053 // already processed all events that we waited for
2054 mKeyIsWaitingForEventsTimeout = std::nullopt;
2055 return false;
2056 }
2057
2058 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2059 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002060 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002061 mKeyIsWaitingForEventsTimeout = currentTime +
2062 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2063 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 return true;
2065 }
2066
2067 // We still have pending events, and already started the timer
2068 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2069 return true; // Still waiting
2070 }
2071
2072 // Waited too long, and some connection still hasn't processed all motions
2073 // Just send the key to the focused window
2074 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2075 focusedWindowName);
2076 mKeyIsWaitingForEventsTimeout = std::nullopt;
2077 return false;
2078}
2079
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002080sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2081 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2082 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002083 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002084 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
Tiger Huang721e26f2018-07-24 22:26:19 +08002086 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002087 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002088 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002089 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2090
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 // If there is no currently focused window and no focused application
2092 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002093 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2094 ALOGI("Dropping %s event because there is no focused window or focused application in "
2095 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002096 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002097 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
2099
Vishnu Nair062a8672021-09-03 16:07:44 -07002100 // Drop key events if requested by input feature
2101 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002102 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002103 }
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2106 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2107 // start interacting with another application via touch (app switch). This code can be removed
2108 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2109 // an app is expected to have a focused window.
2110 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2111 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2112 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002113 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2114 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2115 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002117 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 ALOGW("Waiting because no window has focus but %s may eventually add a "
2119 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002120 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002122 outInjectionResult = InputEventInjectionResult::PENDING;
2123 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002124 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2125 // Already raised ANR. Drop the event
2126 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002127 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002128 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002129 } else {
2130 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002131 outInjectionResult = InputEventInjectionResult::PENDING;
2132 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002133 }
2134 }
2135
2136 // we have a valid, non-null focused window
2137 resetNoFocusedWindowTimeoutLocked();
2138
Prabir Pradhan5735a322022-04-11 17:23:34 +00002139 // Verify targeted injection.
2140 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2141 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002142 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2143 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 }
2145
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002146 if (focusedWindowHandle->getInfo()->inputConfig.test(
2147 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002148 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002149 outInjectionResult = InputEventInjectionResult::PENDING;
2150 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 }
2152
2153 // If the event is a key event, then we must wait for all previous events to
2154 // complete before delivering it because previous events may have the
2155 // side-effect of transferring focus to a different window and we want to
2156 // ensure that the following keys are sent to the new window.
2157 //
2158 // Suppose the user touches a button in a window then immediately presses "A".
2159 // If the button causes a pop-up window to appear then we want to ensure that
2160 // the "A" key is delivered to the new pop-up window. This is because users
2161 // often anticipate pending UI changes when typing on a keyboard.
2162 // To obtain this behavior, we must serialize key events with respect to all
2163 // prior input events.
2164 if (entry.type == EventEntry::Type::KEY) {
2165 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2166 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002167 outInjectionResult = InputEventInjectionResult::PENDING;
2168 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002172 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2173 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174}
2175
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176/**
2177 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2178 * that are currently unresponsive.
2179 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002180std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2181 const std::vector<Monitor>& monitors) const {
2182 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002183 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002184 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002185 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002186 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002187 if (connection == nullptr) {
2188 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002189 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002190 return false;
2191 }
2192 if (!connection->responsive) {
2193 ALOGW("Unresponsive monitor %s will not get the new gesture",
2194 connection->inputChannel->getName().c_str());
2195 return false;
2196 }
2197 return true;
2198 });
2199 return responsiveMonitors;
2200}
2201
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002202/**
2203 * In general, touch should be always split between windows. Some exceptions:
2204 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002205 * from the same device, *and* the window that's receiving the current pointer does not support
2206 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002207 * 2. Don't split mouse events
2208 */
2209bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2210 const MotionEntry& entry) const {
2211 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2212 // We should never split mouse events
2213 return false;
2214 }
2215 for (const TouchedWindow& touchedWindow : touchState.windows) {
2216 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2217 // Spy windows should not affect whether or not touch is split.
2218 continue;
2219 }
2220 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2221 continue;
2222 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002223 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2224 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2225 // Wallpaper window should not affect whether or not touch is split
2226 continue;
2227 }
2228
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002229 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002230 return false;
2231 }
2232 }
2233 return true;
2234}
2235
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002236std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002237 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2238 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002239 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002241 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // For security reasons, we defer updating the touch state until we are sure that
2243 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 const int32_t displayId = entry.displayId;
2245 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002246 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247
2248 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002249 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 // Copy current touch state into tempTouchState.
2252 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2253 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002254 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002256 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2257 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002258 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002259 }
2260
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002261 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002262 bool switchedDevice = false;
2263 if (oldState != nullptr) {
2264 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2265 const bool anotherDeviceIsActive =
2266 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2267 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002268 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002269
2270 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2272 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002273 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2274 // touchable windows.
2275 const bool wasDown = oldState != nullptr && oldState->isDown();
2276 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2277 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002278 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2279 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2280 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002281 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002282
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002283 // If pointers are already down, let's finish the current gesture and ignore the new events
2284 // from another device. However, if the new event is a down event, let's cancel the current
2285 // touch and let the new one take over.
2286 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002287 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002288 << " is already down in display " << displayId << ": " << entry.getDescription();
2289 // TODO(b/211379801): test multiple simultaneous input streams.
2290 outInjectionResult = InputEventInjectionResult::FAILED;
2291 return {}; // wrong device
2292 }
2293
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002295 // If a new gesture is starting, clear the touch state completely.
2296 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002298 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002299 ALOGI("Dropping move event because a pointer for a different device is already active "
2300 "in display %" PRId32,
2301 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002302 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002303 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002304 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002307 if (isHoverAction) {
2308 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2309 // all of the existing hovering pointers and recompute.
2310 tempTouchState.clearHoveringPointers();
2311 }
2312
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2314 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002315 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002316 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002317 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2318 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002319 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002320 auto [newTouchedWindowHandle, outsideTargets] =
2321 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002322
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002323 if (isDown) {
2324 targets += outsideTargets;
2325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002327 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002328 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002330 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 }
2332
Prabir Pradhan5735a322022-04-11 17:23:34 +00002333 // Verify targeted injection.
2334 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2335 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002336 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002337 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002338 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002339 }
2340
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002341 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002343 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2344 // New window supports splitting, but we should never split mouse events.
2345 isSplit = !isFromMouse;
2346 } else if (isSplit) {
2347 // New window does not support splitting but we have already split events.
2348 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 newTouchedWindowHandle = nullptr;
2350 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002351 } else {
2352 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002353 // be delivered to a new window which supports split touch. Pointers from a mouse device
2354 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002355 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002356 }
2357
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002358 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002359 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002360 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002361 // Process the foreground window first so that it is the first to receive the event.
2362 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002363 }
2364
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002365 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002366 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2367 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002368 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002369 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002370 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002371 }
2372
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002374 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002375 continue;
2376 }
2377
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002378 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2379 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002380 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002381 // The "windowHandle" is the target of this hovering pointer.
2382 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002383 }
2384
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002386 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002388 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2389 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002390 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002391 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392
2393 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002394 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002395 }
2396 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002397 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002399 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002401
2402 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002403 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002404 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002405 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002406 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002407
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002408 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2409 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2410
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002411 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2412 // still add a window to the touch state. We should avoid doing that, but some of the
2413 // later checks ("at least one foreground window") rely on this in order to dispatch
2414 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002415 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002416 isDownOrPointerDown
2417 ? std::make_optional(entry.eventTime)
2418 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002419
2420 // If this is the pointer going down and the touched window has a wallpaper
2421 // then also add the touched wallpaper windows so they are locked in for the duration
2422 // of the touch gesture.
2423 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2424 // engine only supports touch events. We would need to add a mechanism similar
2425 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002426 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002427 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2428 windowHandle->getInfo()->inputConfig.test(
2429 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2430 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2431 if (wallpaper != nullptr) {
2432 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2433 InputTarget::Flags::WINDOW_IS_OBSCURED |
2434 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2435 InputTarget::Flags::DISPATCH_AS_IS;
2436 if (isSplit) {
2437 wallpaperFlags |= InputTarget::Flags::SPLIT;
2438 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002439 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2440 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002441 }
2442 }
2443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002445
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002446 // If a window is already pilfering some pointers, give it this new pointer as well and
2447 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2448 // which is a specific behaviour that we want.
2449 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2450 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002451 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2452 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002453 // This window is already pilfering some pointers, and this new pointer is also
2454 // going to it. Therefore, take over this pointer and don't give it to anyone
2455 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002456 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002457 }
2458 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002459
2460 // Restrict all pilfered pointers to the pilfering windows.
2461 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 } else {
2463 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2464
2465 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002466 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002467 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2468 "dropped the pointer down event in display "
2469 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002470 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002471 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 }
2473
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002474 // If the pointer is not currently hovering, then ignore the event.
2475 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2476 const int32_t pointerId = entry.pointerProperties[0].id;
2477 if (oldState == nullptr ||
2478 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2479 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2480 "display "
2481 << displayId << ": " << entry.getDescription();
2482 outInjectionResult = InputEventInjectionResult::FAILED;
2483 return {};
2484 }
2485 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2486 }
2487
arthurhung6d4bed92021-03-17 11:59:33 +08002488 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002489
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002491 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002492 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002493 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002494 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002495 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002496 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002497 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002498 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002499
Prabir Pradhan5735a322022-04-11 17:23:34 +00002500 // Verify targeted injection.
2501 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2502 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002503 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002504 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002505 }
2506
Vishnu Nair062a8672021-09-03 16:07:44 -07002507 // Drop touch events if requested by input feature
2508 if (newTouchedWindowHandle != nullptr &&
2509 shouldDropInput(entry, newTouchedWindowHandle)) {
2510 newTouchedWindowHandle = nullptr;
2511 }
2512
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002513 if (newTouchedWindowHandle != nullptr &&
2514 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002515 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2516 oldTouchedWindowHandle->getName().c_str(),
2517 newTouchedWindowHandle->getName().c_str(), displayId);
2518
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002520 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002521 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002522 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002523
2524 const TouchedWindow& touchedWindow =
2525 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2526 addWindowTargetLocked(oldTouchedWindowHandle,
2527 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002528 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529
2530 // Make a slippery entrance into the new window.
2531 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002532 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002535 ftl::Flags<InputTarget::Flags> targetFlags =
2536 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002537 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002538 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002541 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
2543 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002544 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002545 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002546 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002549 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2550 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002551
2552 // Check if the wallpaper window should deliver the corresponding event.
2553 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002554 tempTouchState, entry.deviceId, pointerId, targets);
2555 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2556 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558 }
Arthur Hung96483742022-11-15 03:30:48 +00002559
2560 // Update the pointerIds for non-splittable when it received pointer down.
2561 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2562 // If no split, we suppose all touched windows should receive pointer down.
2563 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2564 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2565 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2566 // Ignore drag window for it should just track one pointer.
2567 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2568 continue;
2569 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002570 touchedWindow.addTouchingPointer(entry.deviceId,
2571 entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002572 }
2573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 }
2575
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002576 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002577 {
2578 std::vector<TouchedWindow> hoveringWindows =
2579 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2580 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002581 std::optional<InputTarget> target =
2582 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002583 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002584 if (!target) {
2585 continue;
2586 }
2587 // Hardcode to single hovering pointer for now.
2588 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2589 pointerIds.set(entry.pointerProperties[0].id);
2590 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2591 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594
Prabir Pradhan5735a322022-04-11 17:23:34 +00002595 // Ensure that all touched windows are valid for injection.
2596 if (entry.injectionState != nullptr) {
2597 std::string errs;
2598 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002599 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2600 if (err) errs += "\n - " + *err;
2601 }
2602 if (!errs.empty()) {
2603 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002604 "%s:%s",
2605 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002606 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002607 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002608 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002609 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002610
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002611 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2612 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002614 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002615 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002616 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002617 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002618 for (InputTarget& target : targets) {
2619 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2620 sp<WindowInfoHandle> targetWindow =
2621 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2622 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2623 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 }
2626 }
2627 }
2628 }
2629
Harry Cuttsb166c002023-05-09 13:06:05 +00002630 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2631 // only want the system UI to handle these gestures.
2632 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2633 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2634 if (isTouchpadNavGesture) {
2635 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2636 }
2637
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002638 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002639 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002640 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2641 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002642 // Windows with hovering pointers are getting persisted inside TouchState.
2643 // Do not send this event to those windows.
2644 continue;
2645 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002646
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002647 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002648 touchedWindow.getTouchingPointers(entry.deviceId),
2649 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002650 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002651
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002652 // During targeted injection, only allow owned targets to receive events
2653 std::erase_if(targets, [&](const InputTarget& target) {
2654 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2655 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2656 if (err) {
2657 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2658 << ": " << (*err);
2659 return true;
2660 }
2661 return false;
2662 });
2663
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002664 if (targets.empty()) {
2665 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2666 outInjectionResult = InputEventInjectionResult::FAILED;
2667 return {};
2668 }
2669
2670 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2671 // window that is actually receiving the entire gesture.
2672 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2673 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2674 })) {
2675 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2676 << entry.getDescription();
2677 outInjectionResult = InputEventInjectionResult::FAILED;
2678 return {};
2679 }
2680
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002681 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002682 // Drop the outside or hover touch windows since we will not care about them
2683 // in the next iteration.
2684 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002687 if (switchedDevice) {
2688 if (DEBUG_FOCUS) {
2689 ALOGD("Conflicting pointer actions: Switched to a different device.");
2690 }
2691 *outConflictingPointerActions = true;
2692 }
2693
2694 if (isHoverAction) {
2695 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002696 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002697 ALOGD_IF(DEBUG_FOCUS,
2698 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002699 *outConflictingPointerActions = true;
2700 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002701 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2702 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002703 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002704 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2705 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002706 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002707 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002708 // All pointers up or canceled.
2709 tempTouchState.reset();
2710 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2711 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002712 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2713 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002715 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002716 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2717 // One pointer went up.
2718 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2719 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002721 for (size_t i = 0; i < tempTouchState.windows.size();) {
2722 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002723 touchedWindow.removeTouchingPointer(entry.deviceId, pointerId);
2724 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002725 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2726 continue;
2727 }
2728 i += 1;
2729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 }
2731
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002732 // Save changes unless the action was scroll in which case the temporary touch
2733 // state was only valid for this one action.
2734 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002735 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002736 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 mTouchStatesByDisplay[displayId] = tempTouchState;
2738 } else {
2739 mTouchStatesByDisplay.erase(displayId);
2740 }
2741 }
2742
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002743 if (tempTouchState.windows.empty()) {
2744 mTouchStatesByDisplay.erase(displayId);
2745 }
2746
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002747 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748}
2749
arthurhung6d4bed92021-03-17 11:59:33 +08002750void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002751 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2752 // have an explicit reason to support it.
2753 constexpr bool isStylus = false;
2754
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002755 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002756 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002757 if (dropWindow) {
2758 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002759 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002760 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002761 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002762 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002763 }
2764 mDragState.reset();
2765}
2766
2767void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002768 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002769 return;
2770 }
2771
arthurhung6d4bed92021-03-17 11:59:33 +08002772 if (!mDragState->isStartDrag) {
2773 mDragState->isStartDrag = true;
2774 mDragState->isStylusButtonDownAtStart =
2775 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2776 }
2777
Arthur Hung54745652022-04-20 07:17:41 +00002778 // Find the pointer index by id.
2779 int32_t pointerIndex = 0;
2780 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2781 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2782 if (pointerProperties.id == mDragState->pointerId) {
2783 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002784 }
Arthur Hung54745652022-04-20 07:17:41 +00002785 }
arthurhung6d4bed92021-03-17 11:59:33 +08002786
Arthur Hung54745652022-04-20 07:17:41 +00002787 if (uint32_t(pointerIndex) == entry.pointerCount) {
2788 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002789 }
2790
2791 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2792 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2793 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2794
2795 switch (maskedAction) {
2796 case AMOTION_EVENT_ACTION_MOVE: {
2797 // Handle the special case : stylus button no longer pressed.
2798 bool isStylusButtonDown =
2799 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2800 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2801 finishDragAndDrop(entry.displayId, x, y);
2802 return;
2803 }
2804
2805 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2806 // until we have an explicit reason to support it.
2807 constexpr bool isStylus = false;
2808
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002809 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002810 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002811 // enqueue drag exit if needed.
2812 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2813 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2814 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002815 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002816 y);
2817 }
2818 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2819 }
2820 // enqueue drag location if needed.
2821 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002822 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002823 }
2824 break;
2825 }
2826
2827 case AMOTION_EVENT_ACTION_POINTER_UP:
2828 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2829 break;
2830 }
2831 // The drag pointer is up.
2832 [[fallthrough]];
2833 case AMOTION_EVENT_ACTION_UP:
2834 finishDragAndDrop(entry.displayId, x, y);
2835 break;
2836 case AMOTION_EVENT_ACTION_CANCEL: {
2837 ALOGD("Receiving cancel when drag and drop.");
2838 sendDropWindowCommandLocked(nullptr, 0, 0);
2839 mDragState.reset();
2840 break;
2841 }
arthurhungb89ccb02020-12-30 16:19:01 +08002842 }
2843}
2844
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002845std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2846 const sp<android::gui::WindowInfoHandle>& windowHandle,
2847 ftl::Flags<InputTarget::Flags> targetFlags,
2848 std::optional<nsecs_t> firstDownTimeInTarget) const {
2849 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2850 if (inputChannel == nullptr) {
2851 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2852 return {};
2853 }
2854 InputTarget inputTarget;
2855 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002856 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002857 inputTarget.flags = targetFlags;
2858 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2859 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2860 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2861 if (displayInfoIt != mDisplayInfos.end()) {
2862 inputTarget.displayTransform = displayInfoIt->second.transform;
2863 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002864 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002865 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2866 }
2867 return inputTarget;
2868}
2869
chaviw98318de2021-05-19 16:45:23 -05002870void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002871 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002872 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002873 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002874 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002875 std::vector<InputTarget>::iterator it =
2876 std::find_if(inputTargets.begin(), inputTargets.end(),
2877 [&windowHandle](const InputTarget& inputTarget) {
2878 return inputTarget.inputChannel->getConnectionToken() ==
2879 windowHandle->getToken();
2880 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002881
chaviw98318de2021-05-19 16:45:23 -05002882 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883
2884 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002885 std::optional<InputTarget> target =
2886 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2887 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002888 return;
2889 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002890 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002891 it = inputTargets.end() - 1;
2892 }
2893
2894 ALOG_ASSERT(it->flags == targetFlags);
2895 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2896
chaviw1ff3d1e2020-07-01 15:53:47 -07002897 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898}
2899
Michael Wright3dd60e22019-03-27 22:06:44 +00002900void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002901 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002902 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2903 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002904
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002905 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2906 InputTarget target;
2907 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002908 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002909 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2910 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002911 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2912 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002913 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002914 target.setDefaultPointerTransform(target.displayTransform);
2915 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 }
2917}
2918
Robert Carrc9bf1d32020-04-13 17:21:08 -07002919/**
2920 * Indicate whether one window handle should be considered as obscuring
2921 * another window handle. We only check a few preconditions. Actually
2922 * checking the bounds is left to the caller.
2923 */
chaviw98318de2021-05-19 16:45:23 -05002924static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2925 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002926 // Compare by token so cloned layers aren't counted
2927 if (haveSameToken(windowHandle, otherHandle)) {
2928 return false;
2929 }
2930 auto info = windowHandle->getInfo();
2931 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002932 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002933 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002934 } else if (otherInfo->alpha == 0 &&
2935 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002936 // Those act as if they were invisible, so we don't need to flag them.
2937 // We do want to potentially flag touchable windows even if they have 0
2938 // opacity, since they can consume touches and alter the effects of the
2939 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002940 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002941 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2942 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002943 } else if (info->ownerUid == otherInfo->ownerUid) {
2944 // If ownerUid is the same we don't generate occlusion events as there
2945 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002946 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002948 return false;
2949 } else if (otherInfo->displayId != info->displayId) {
2950 return false;
2951 }
2952 return true;
2953}
2954
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002955/**
2956 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2957 * untrusted, one should check:
2958 *
2959 * 1. If result.hasBlockingOcclusion is true.
2960 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2961 * BLOCK_UNTRUSTED.
2962 *
2963 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2964 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2965 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2966 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2967 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2968 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2969 *
2970 * If neither of those is true, then it means the touch can be allowed.
2971 */
2972InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002973 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2974 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002975 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002976 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002977 TouchOcclusionInfo info;
2978 info.hasBlockingOcclusion = false;
2979 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002980 info.obscuringUid = gui::Uid::INVALID;
2981 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002982 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002983 if (windowHandle == otherHandle) {
2984 break; // All future windows are below us. Exit early.
2985 }
chaviw98318de2021-05-19 16:45:23 -05002986 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002987 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2988 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002989 if (DEBUG_TOUCH_OCCLUSION) {
2990 info.debugInfo.push_back(
2991 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2992 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002993 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2994 // we perform the checks below to see if the touch can be propagated or not based on the
2995 // window's touch occlusion mode
2996 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2997 info.hasBlockingOcclusion = true;
2998 info.obscuringUid = otherInfo->ownerUid;
2999 info.obscuringPackage = otherInfo->packageName;
3000 break;
3001 }
3002 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003003 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003004 float opacity =
3005 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3006 // Given windows A and B:
3007 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3008 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3009 opacityByUid[uid] = opacity;
3010 if (opacity > info.obscuringOpacity) {
3011 info.obscuringOpacity = opacity;
3012 info.obscuringUid = uid;
3013 info.obscuringPackage = otherInfo->packageName;
3014 }
3015 }
3016 }
3017 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003018 if (DEBUG_TOUCH_OCCLUSION) {
3019 info.debugInfo.push_back(
3020 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3021 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003022 return info;
3023}
3024
chaviw98318de2021-05-19 16:45:23 -05003025std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003026 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003027 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003028 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3029 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3030 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003031 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003032 info->ownerUid.toString().c_str(), info->id,
3033 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3034 info->frameTop, info->frameRight, info->frameBottom,
3035 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3036 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3037 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003038 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003039}
3040
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003041bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3042 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003043 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3044 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003045 return false;
3046 }
3047 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003048 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003049 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003050 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003051 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3052 return false;
3053 }
3054 return true;
3055}
3056
chaviw98318de2021-05-19 16:45:23 -05003057bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003060 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3061 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003062 if (windowHandle == otherHandle) {
3063 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
chaviw98318de2021-05-19 16:45:23 -05003065 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003066 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003067 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 return true;
3069 }
3070 }
3071 return false;
3072}
3073
chaviw98318de2021-05-19 16:45:23 -05003074bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003075 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003076 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3077 const WindowInfo* windowInfo = windowHandle->getInfo();
3078 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003079 if (windowHandle == otherHandle) {
3080 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003081 }
chaviw98318de2021-05-19 16:45:23 -05003082 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003083 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003084 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003085 return true;
3086 }
3087 }
3088 return false;
3089}
3090
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003091std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003092 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003093 if (applicationHandle != nullptr) {
3094 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003095 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 } else {
3097 return applicationHandle->getName();
3098 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003099 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003100 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003102 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
3104}
3105
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003106void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003107 if (!isUserActivityEvent(eventEntry)) {
3108 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003109 return;
3110 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003111 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003112 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003113 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003114 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003115 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003116 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003117 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
3119 }
3120
3121 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003123 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003124 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3125 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 return;
3127 }
Josep del Riob3981622023-04-18 15:49:45 +00003128 if (windowDisablingUserActivityInfo != nullptr) {
3129 if (DEBUG_DISPATCH_CYCLE) {
3130 ALOGD("Not poking user activity: disabled by window '%s'.",
3131 windowDisablingUserActivityInfo->name.c_str());
3132 }
3133 return;
3134 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003135 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 eventType = USER_ACTIVITY_EVENT_TOUCH;
3137 }
3138 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003140 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003141 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3142 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 return;
3144 }
Josep del Riob3981622023-04-18 15:49:45 +00003145 // If the key code is unknown, we don't consider it user activity
3146 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3147 return;
3148 }
3149 // Don't inhibit events that were intercepted or are not passed to
3150 // the apps, like system shortcuts
3151 if (windowDisablingUserActivityInfo != nullptr &&
3152 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3153 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3154 if (DEBUG_DISPATCH_CYCLE) {
3155 ALOGD("Not poking user activity: disabled by window '%s'.",
3156 windowDisablingUserActivityInfo->name.c_str());
3157 }
3158 return;
3159 }
3160
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 eventType = USER_ACTIVITY_EVENT_BUTTON;
3162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003164 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003165 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003166 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003167 break;
3168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 }
3170
Prabir Pradhancef936d2021-07-21 16:17:52 +00003171 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3172 REQUIRES(mLock) {
3173 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003174 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003175 };
3176 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177}
3178
3179void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003180 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003182 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003183 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003185 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003186 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003187 ATRACE_NAME(message.c_str());
3188 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003189 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003191 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003193 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003194 inputTarget.getPointerInfoString().c_str());
3195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196
3197 // Skip this event if the connection status is not normal.
3198 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003199 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 if (DEBUG_DISPATCH_CYCLE) {
3201 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003202 connection->getInputChannelName().c_str(),
3203 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 return;
3206 }
3207
3208 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003209 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003210 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003211 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003212 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003215 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003216 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3217 logDispatchStateLocked();
3218 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3219 "target on connection "
3220 << connection->getInputChannelName() << " for "
3221 << originalMotionEntry.getDescription();
3222 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003224 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3225 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 if (!splitMotionEntry) {
3227 return; // split event was dropped
3228 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003229 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3230 std::string reason = std::string("reason=pointer cancel on split window");
3231 android_log_event_list(LOGTAG_INPUT_CANCEL)
3232 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3233 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003234 if (DEBUG_FOCUS) {
3235 ALOGD("channel '%s' ~ Split motion event.",
3236 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003237 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003238 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3240 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 return;
3242 }
3243 }
3244
3245 // Not splitting. Enqueue dispatch entries for the event as is.
3246 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3247}
3248
3249void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003250 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003251 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003252 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003253 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003255 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003256 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003257 ATRACE_NAME(message.c_str());
3258 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003259 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3260 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003261
hongzuo liu95785e22022-09-06 02:51:35 +00003262 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263
3264 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003265 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003267 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003269 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003270 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
3278 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003279 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 startDispatchCycleLocked(currentTime, connection);
3281 }
3282}
3283
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003284void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003286 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003287 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003288 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3290 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003291 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003292 ATRACE_NAME(message.c_str());
3293 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3295 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 return;
3297 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298
3299 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3300 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 // This is a new event.
3303 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003304 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003305 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3308 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003314 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003315 dispatchEntry->resolvedAction = keyEntry.action;
3316 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3319 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003320 LOG(WARNING) << "channel " << connection->getInputChannelName()
3321 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 return; // skip the inconsistent event
3323 }
3324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003327 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003328 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003329 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3330 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3331 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3332 static_cast<int32_t>(IdGenerator::Source::OTHER);
3333 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003342 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3344 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003345 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003346 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 }
3348 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003349 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3350 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003351 if (DEBUG_DISPATCH_CYCLE) {
3352 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3353 "enter event",
3354 connection->getInputChannelName().c_str());
3355 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003356 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3357 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003361 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003362 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3364 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003365 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3367 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003368 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3373 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003374 LOG(WARNING) << "channel " << connection->getInputChannelName()
3375 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 return; // skip the inconsistent event
3377 }
3378
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003379 dispatchEntry->resolvedEventId =
3380 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3381 ? mIdGenerator.nextId()
3382 : motionEntry.id;
3383 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3384 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3385 ") to MotionEvent(id=0x%" PRIx32 ").",
3386 motionEntry.id, dispatchEntry->resolvedEventId);
3387 ATRACE_NAME(message.c_str());
3388 }
3389
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003390 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3391 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3392 // Skip reporting pointer down outside focus to the policy.
3393 break;
3394 }
3395
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003396 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003397 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398
3399 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003401 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003402 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003403 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3404 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003405 break;
3406 }
Chris Yef59a2f42020-10-16 12:55:26 -07003407 case EventEntry::Type::SENSOR: {
3408 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3409 break;
3410 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 case EventEntry::Type::CONFIGURATION_CHANGED:
3412 case EventEntry::Type::DEVICE_RESET: {
3413 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003414 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003415 break;
3416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 }
3418
3419 // Remember that we are waiting for this dispatch to complete.
3420 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003421 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
3423
3424 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003425 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003426 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003427}
3428
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003429/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003430 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003431 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003432 * The first role is to log input interaction with windows, which helps determine what the user was
3433 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3434 * that user started interacting with launcher window, as well as any other window that received
3435 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3436 * when the set of tokens that received the event changes. It is not logged again as long as the
3437 * user is interacting with the same windows.
3438 *
3439 * The second role is to track input device activity for metrics collection. For each input event,
3440 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3441 * input_interaction logs, the device interaction is reported even when the set of interaction
3442 * tokens do not change.
3443 *
3444 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3445 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003446 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003447void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3448 const std::vector<InputTarget>& targets) {
3449 int32_t deviceId;
3450 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003451 // Skip ACTION_UP events, and all events other than keys and motions
3452 if (entry.type == EventEntry::Type::KEY) {
3453 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3454 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3455 return;
3456 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003457 deviceId = keyEntry.deviceId;
3458 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003459 } else if (entry.type == EventEntry::Type::MOTION) {
3460 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3461 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003462 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3463 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003464 return;
3465 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003466 deviceId = motionEntry.deviceId;
3467 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003468 } else {
3469 return; // Not a key or a motion
3470 }
3471
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003472 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003473 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003474 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003475 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003476 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003477 continue; // Skip windows that receive ACTION_OUTSIDE
3478 }
3479
3480 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003481 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003482 if (connection == nullptr) {
3483 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003484 }
3485 newConnectionTokens.insert(std::move(token));
3486 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003487 if (target.windowHandle) {
3488 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3489 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003490 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003491
3492 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3493 REQUIRES(mLock) {
3494 scoped_unlock unlock(mLock);
3495 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3496 };
3497 postCommandLocked(std::move(command));
3498
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003499 if (newConnectionTokens == mInteractionConnectionTokens) {
3500 return; // no change
3501 }
3502 mInteractionConnectionTokens = newConnectionTokens;
3503
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003504 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003505 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003506 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003507 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003508 std::string message = "Interaction with: " + targetList;
3509 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003510 message += "<none>";
3511 }
3512 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3513}
3514
chaviwfd6d3512019-03-25 13:23:49 -07003515void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003516 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003517 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003518 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3519 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003520 return;
3521 }
3522
Vishnu Nairc519ff72021-01-21 08:23:08 -08003523 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003524 if (focusedToken == token) {
3525 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003526 return;
3527 }
3528
Prabir Pradhancef936d2021-07-21 16:17:52 +00003529 auto command = [this, token]() REQUIRES(mLock) {
3530 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003531 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003532 };
3533 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534}
3535
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003536status_t InputDispatcher::publishMotionEvent(Connection& connection,
3537 DispatchEntry& dispatchEntry) const {
3538 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3539 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3540
3541 PointerCoords scaledCoords[MAX_POINTERS];
3542 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3543
3544 // Set the X and Y offset and X and Y scale depending on the input source.
3545 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003546 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003547 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3548 if (globalScaleFactor != 1.0f) {
3549 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3550 scaledCoords[i] = motionEntry.pointerCoords[i];
3551 // Don't apply window scale here since we don't want scale to affect raw
3552 // coordinates. The scale will be sent back to the client and applied
3553 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003554 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003555 }
3556 usingCoords = scaledCoords;
3557 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003558 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003559 // We don't want the dispatch target to know the coordinates
3560 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3561 scaledCoords[i].clear();
3562 }
3563 usingCoords = scaledCoords;
3564 }
3565
3566 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3567
3568 // Publish the motion event.
3569 return connection.inputPublisher
3570 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3571 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3572 std::move(hmac), dispatchEntry.resolvedAction,
3573 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3574 motionEntry.edgeFlags, motionEntry.metaState,
3575 motionEntry.buttonState, motionEntry.classification,
3576 dispatchEntry.transform, motionEntry.xPrecision,
3577 motionEntry.yPrecision, motionEntry.xCursorPosition,
3578 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3579 motionEntry.downTime, motionEntry.eventTime,
3580 motionEntry.pointerCount, motionEntry.pointerProperties,
3581 usingCoords);
3582}
3583
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003585 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003586 if (ATRACE_ENABLED()) {
3587 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003589 ATRACE_NAME(message.c_str());
3590 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003591 if (DEBUG_DISPATCH_CYCLE) {
3592 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003595 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003596 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003598 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003599 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600
3601 // Publish the event.
3602 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003603 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3604 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003605 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003606 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3607 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003608 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3609 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3610 << connection->getInputChannelName();
3611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003614 status = connection->inputPublisher
3615 .publishKeyEvent(dispatchEntry->seq,
3616 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3617 keyEntry.source, keyEntry.displayId,
3618 std::move(hmac), dispatchEntry->resolvedAction,
3619 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3620 keyEntry.scanCode, keyEntry.metaState,
3621 keyEntry.repeatCount, keyEntry.downTime,
3622 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 }
3625
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003626 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003627 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3628 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3629 << connection->getInputChannelName();
3630 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003631 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003632 break;
3633 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003634
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003635 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003636 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003637 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003638 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003639 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003640 break;
3641 }
3642
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003643 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3644 const TouchModeEntry& touchModeEntry =
3645 static_cast<const TouchModeEntry&>(eventEntry);
3646 status = connection->inputPublisher
3647 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3648 touchModeEntry.inTouchMode);
3649
3650 break;
3651 }
3652
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3654 const auto& captureEntry =
3655 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3656 status = connection->inputPublisher
3657 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003658 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003659 break;
3660 }
3661
arthurhungb89ccb02020-12-30 16:19:01 +08003662 case EventEntry::Type::DRAG: {
3663 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3664 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3665 dragEntry.id, dragEntry.x,
3666 dragEntry.y,
3667 dragEntry.isExiting);
3668 break;
3669 }
3670
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003671 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003672 case EventEntry::Type::DEVICE_RESET:
3673 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003674 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003675 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
3679
3680 // Check the result.
3681 if (status) {
3682 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003683 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003685 "This is unexpected because the wait queue is empty, so the pipe "
3686 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003687 "event to it, status=%s(%d)",
3688 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3689 status);
Harry Cutts33476232023-01-30 19:57:29 +00003690 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 } else {
3692 // Pipe is full and we are waiting for the app to finish process some events
3693 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003694 if (DEBUG_DISPATCH_CYCLE) {
3695 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3696 "waiting for the application to catch up",
3697 connection->getInputChannelName().c_str());
3698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 }
3700 } else {
3701 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003702 "status=%s(%d)",
3703 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3704 status);
Harry Cutts33476232023-01-30 19:57:29 +00003705 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
3707 return;
3708 }
3709
3710 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003711 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3712 connection->outboundQueue.end(),
3713 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003714 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003715 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003716 if (connection->responsive) {
3717 mAnrTracker.insert(dispatchEntry->timeoutTime,
3718 connection->inputChannel->getConnectionToken());
3719 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003720 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 }
3722}
3723
chaviw09c8d2d2020-08-24 15:48:26 -07003724std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3725 size_t size;
3726 switch (event.type) {
3727 case VerifiedInputEvent::Type::KEY: {
3728 size = sizeof(VerifiedKeyEvent);
3729 break;
3730 }
3731 case VerifiedInputEvent::Type::MOTION: {
3732 size = sizeof(VerifiedMotionEvent);
3733 break;
3734 }
3735 }
3736 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3737 return mHmacKeyManager.sign(start, size);
3738}
3739
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003740const std::array<uint8_t, 32> InputDispatcher::getSignature(
3741 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003742 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003743 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003744 // Only sign events up and down events as the purely move events
3745 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003746 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003747 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003748
3749 VerifiedMotionEvent verifiedEvent =
3750 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3751 verifiedEvent.actionMasked = actionMasked;
3752 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3753 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003754}
3755
3756const std::array<uint8_t, 32> InputDispatcher::getSignature(
3757 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3758 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3759 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3760 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003761 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003762}
3763
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003765 const std::shared_ptr<Connection>& connection,
3766 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003767 if (DEBUG_DISPATCH_CYCLE) {
3768 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3769 connection->getInputChannelName().c_str(), seq, toString(handled));
3770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003772 if (connection->status == Connection::Status::BROKEN ||
3773 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 return;
3775 }
3776
3777 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003778 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3779 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3780 };
3781 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782}
3783
3784void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003785 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003787 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003788 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3789 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791
3792 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003793 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003794 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003795 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003796 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797
3798 // The connection appears to be unrecoverably broken.
3799 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003800 if (connection->status == Connection::Status::NORMAL) {
3801 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802
3803 if (notify) {
3804 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003805 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3806 connection->getInputChannelName().c_str());
3807
3808 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003809 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003810 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003811 };
3812 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814 }
3815}
3816
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003817void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3818 while (!queue.empty()) {
3819 DispatchEntry* dispatchEntry = queue.front();
3820 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003821 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
3823}
3824
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003825void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003827 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829 delete dispatchEntry;
3830}
3831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003832int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3833 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003834 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003835 if (connection == nullptr) {
3836 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3837 connectionToken.get(), events);
3838 return 0; // remove the callback
3839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003841 bool notify;
3842 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3843 if (!(events & ALOOPER_EVENT_INPUT)) {
3844 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3845 "events=0x%x",
3846 connection->getInputChannelName().c_str(), events);
3847 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003850 nsecs_t currentTime = now();
3851 bool gotOne = false;
3852 status_t status = OK;
3853 for (;;) {
3854 Result<InputPublisher::ConsumerResponse> result =
3855 connection->inputPublisher.receiveConsumerResponse();
3856 if (!result.ok()) {
3857 status = result.error().code();
3858 break;
3859 }
3860
3861 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3862 const InputPublisher::Finished& finish =
3863 std::get<InputPublisher::Finished>(*result);
3864 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3865 finish.consumeTime);
3866 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003867 if (shouldReportMetricsForConnection(*connection)) {
3868 const InputPublisher::Timeline& timeline =
3869 std::get<InputPublisher::Timeline>(*result);
3870 mLatencyTracker
3871 .trackGraphicsLatency(timeline.inputEventId,
3872 connection->inputChannel->getConnectionToken(),
3873 std::move(timeline.graphicsTimeline));
3874 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 }
3876 gotOne = true;
3877 }
3878 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003879 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003880 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 return 1;
3882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 }
3884
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003885 notify = status != DEAD_OBJECT || !connection->monitor;
3886 if (notify) {
3887 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3888 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3889 status);
3890 }
3891 } else {
3892 // Monitor channels are never explicitly unregistered.
3893 // We do it automatically when the remote endpoint is closed so don't warn about them.
3894 const bool stillHaveWindowHandle =
3895 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3896 notify = !connection->monitor && stillHaveWindowHandle;
3897 if (notify) {
3898 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3899 connection->getInputChannelName().c_str(), events);
3900 }
3901 }
3902
3903 // Remove the channel.
3904 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3905 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906}
3907
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003910 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003911 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 }
3913}
3914
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003915void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003916 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003917 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003918 for (const Monitor& monitor : monitors) {
3919 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003920 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003921 }
3922}
3923
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003925 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003926 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003927 if (connection == nullptr) {
3928 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003930
3931 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932}
3933
3934void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003935 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003936 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 return;
3938 }
3939
3940 nsecs_t currentTime = now();
3941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003942 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003943 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003945 if (cancelationEvents.empty()) {
3946 return;
3947 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003948 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3949 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003950 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003951 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003952 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003953 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003954
Arthur Hungb3307ee2021-10-14 10:57:37 +00003955 std::string reason = std::string("reason=").append(options.reason);
3956 android_log_event_list(LOGTAG_INPUT_CANCEL)
3957 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3958
Svet Ganov5d3bc372020-01-26 23:11:07 -08003959 InputTarget target;
Hu Guoca59f112023-09-17 20:51:08 +08003960 sp<WindowInfoHandle> windowHandle;
3961 if (options.displayId) {
3962 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3963 options.displayId.value());
3964 } else {
3965 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3966 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003967 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003968 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003969 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003970 target.globalScaleFactor = windowInfo->globalScaleFactor;
3971 }
3972 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003973 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003974
hongzuo liu95785e22022-09-06 02:51:35 +00003975 const bool wasEmpty = connection->outboundQueue.empty();
3976
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003977 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003978 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003979 switch (cancelationEventEntry->type) {
3980 case EventEntry::Type::KEY: {
3981 logOutboundKeyDetails("cancel - ",
3982 static_cast<const KeyEntry&>(*cancelationEventEntry));
3983 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003985 case EventEntry::Type::MOTION: {
3986 logOutboundMotionDetails("cancel - ",
3987 static_cast<const MotionEntry&>(*cancelationEventEntry));
3988 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003990 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003991 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003992 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3993 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003994 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003995 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003996 break;
3997 }
3998 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003999 case EventEntry::Type::DEVICE_RESET:
4000 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004001 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004002 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004003 break;
4004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 }
4006
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004007 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004008 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004010
hongzuo liu95785e22022-09-06 02:51:35 +00004011 // If the outbound queue was previously empty, start the dispatch cycle going.
4012 if (wasEmpty && !connection->outboundQueue.empty()) {
4013 startDispatchCycleLocked(currentTime, connection);
4014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015}
4016
Svet Ganov5d3bc372020-01-26 23:11:07 -08004017void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004018 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004019 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004020 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004021 return;
4022 }
4023
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004024 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004025 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026
4027 if (downEvents.empty()) {
4028 return;
4029 }
4030
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004032 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4033 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004035
4036 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004037 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004038 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4039 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004040 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004041 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042 target.globalScaleFactor = windowInfo->globalScaleFactor;
4043 }
4044 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004045 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004046
hongzuo liu95785e22022-09-06 02:51:35 +00004047 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004048 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 switch (downEventEntry->type) {
4050 case EventEntry::Type::MOTION: {
4051 logOutboundMotionDetails("down - ",
4052 static_cast<const MotionEntry&>(*downEventEntry));
4053 break;
4054 }
4055
4056 case EventEntry::Type::KEY:
4057 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004058 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004059 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004060 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004061 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004062 case EventEntry::Type::SENSOR:
4063 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004064 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004065 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004066 break;
4067 }
4068 }
4069
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004070 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004071 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004072 }
4073
hongzuo liu95785e22022-09-06 02:51:35 +00004074 // If the outbound queue was previously empty, start the dispatch cycle going.
4075 if (wasEmpty && !connection->outboundQueue.empty()) {
4076 startDispatchCycleLocked(downTime, connection);
4077 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004078}
4079
Arthur Hungc539dbb2022-12-08 07:45:36 +00004080void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4081 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4082 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004083 std::shared_ptr<Connection> wallpaperConnection =
4084 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004085 if (wallpaperConnection != nullptr) {
4086 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4087 }
4088 }
4089}
4090
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004091std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004092 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4093 nsecs_t splitDownTime) {
4094 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095
4096 uint32_t splitPointerIndexMap[MAX_POINTERS];
4097 PointerProperties splitPointerProperties[MAX_POINTERS];
4098 PointerCoords splitPointerCoords[MAX_POINTERS];
4099
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004100 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 uint32_t splitPointerCount = 0;
4102
4103 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004106 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004108 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4110 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4111 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004112 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 splitPointerCount += 1;
4114 }
4115 }
4116
4117 if (splitPointerCount != pointerIds.count()) {
4118 // This is bad. We are missing some of the pointers that we expected to deliver.
4119 // Most likely this indicates that we received an ACTION_MOVE events that has
4120 // different pointer ids than we expected based on the previous ACTION_DOWN
4121 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4122 // in this way.
4123 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004124 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004125 "a broken sequence of pointer ids from the input device: %s",
4126 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004127 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 }
4129
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004130 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4133 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4135 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004136 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004138 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 if (pointerIds.count() == 1) {
4140 // The first/last pointer went down/up.
4141 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004143 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4144 ? AMOTION_EVENT_ACTION_CANCEL
4145 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 } else {
4147 // A secondary pointer went down/up.
4148 uint32_t splitPointerIndex = 0;
4149 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4150 splitPointerIndex += 1;
4151 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 action = maskedAction |
4153 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 }
4155 } else {
4156 // An unrelated pointer changed.
4157 action = AMOTION_EVENT_ACTION_MOVE;
4158 }
4159 }
4160
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004161 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4162 logDispatchStateLocked();
4163 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4164 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4165 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004166 }
4167
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004168 int32_t newId = mIdGenerator.nextId();
4169 if (ATRACE_ENABLED()) {
4170 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4171 ") to MotionEvent(id=0x%" PRIx32 ").",
4172 originalMotionEntry.id, newId);
4173 ATRACE_NAME(message.c_str());
4174 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004175 std::unique_ptr<MotionEntry> splitMotionEntry =
4176 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4177 originalMotionEntry.deviceId, originalMotionEntry.source,
4178 originalMotionEntry.displayId,
4179 originalMotionEntry.policyFlags, action,
4180 originalMotionEntry.actionButton,
4181 originalMotionEntry.flags, originalMotionEntry.metaState,
4182 originalMotionEntry.buttonState,
4183 originalMotionEntry.classification,
4184 originalMotionEntry.edgeFlags,
4185 originalMotionEntry.xPrecision,
4186 originalMotionEntry.yPrecision,
4187 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004188 originalMotionEntry.yCursorPosition, splitDownTime,
4189 splitPointerCount, splitPointerProperties,
4190 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004192 if (originalMotionEntry.injectionState) {
4193 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 splitMotionEntry->injectionState->refCount += 1;
4195 }
4196
4197 return splitMotionEntry;
4198}
4199
Prabir Pradhan678438e2023-04-13 19:32:51 +00004200void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004201 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004202 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Antonio Kantekf16f2832021-09-28 04:39:20 +00004205 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004207 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004209 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004210 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004211 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 } // release lock
4213
4214 if (needWake) {
4215 mLooper->wake();
4216 }
4217}
4218
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004219/**
4220 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004221 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4222 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4223 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4224 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4225 * potentially handle the back key presses.
4226 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4227 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004228 */
4229void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004231 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4232 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004233 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004234 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004235 }
4236 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004237 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004238 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004239 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004240 keyCode = newKeyCode;
4241 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4242 }
4243 } else if (action == AKEY_EVENT_ACTION_UP) {
4244 // In order to maintain a consistent stream of up and down events, check to see if the key
4245 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4246 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004247 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004248 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004249 auto replacementIt = mReplacedKeys.find(replacement);
4250 if (replacementIt != mReplacedKeys.end()) {
4251 keyCode = replacementIt->second;
4252 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004253 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4254 }
4255 }
4256}
4257
Prabir Pradhan678438e2023-04-13 19:32:51 +00004258void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004259 ALOGD_IF(debugInboundEventDetails(),
4260 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4261 ", deviceId=%d, source=%s, displayId=%" PRId32
4262 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4263 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004264 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4265 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4266 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004267 Result<void> keyCheck = validateKeyEvent(args.action);
4268 if (!keyCheck.ok()) {
4269 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 return;
4271 }
4272
Prabir Pradhan678438e2023-04-13 19:32:51 +00004273 uint32_t policyFlags = args.policyFlags;
4274 int32_t flags = args.flags;
4275 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004276 // InputDispatcher tracks and generates key repeats on behalf of
4277 // whatever notifies it, so repeatCount should always be set to 0
4278 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4280 policyFlags |= POLICY_FLAG_VIRTUAL;
4281 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 if (policyFlags & POLICY_FLAG_FUNCTION) {
4284 metaState |= AMETA_FUNCTION_ON;
4285 }
4286
4287 policyFlags |= POLICY_FLAG_TRUSTED;
4288
Prabir Pradhan678438e2023-04-13 19:32:51 +00004289 int32_t keyCode = args.keyCode;
4290 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004291
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004293 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4294 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4295 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296
Michael Wright2b3c3302018-03-02 17:19:13 +00004297 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004298 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004299 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4300 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004301 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Antonio Kantekf16f2832021-09-28 04:39:20 +00004304 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 { // acquire lock
4306 mLock.lock();
4307
4308 if (shouldSendKeyToInputFilterLocked(args)) {
4309 mLock.unlock();
4310
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004311 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004312 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 return; // event was consumed by the filter
4314 }
4315
4316 mLock.lock();
4317 }
4318
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004320 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4321 args.displayId, policyFlags, args.action, flags, keyCode,
4322 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004324 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 mLock.unlock();
4326 } // release lock
4327
4328 if (needWake) {
4329 mLooper->wake();
4330 }
4331}
4332
Prabir Pradhan678438e2023-04-13 19:32:51 +00004333bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 return mInputFilterEnabled;
4335}
4336
Prabir Pradhan678438e2023-04-13 19:32:51 +00004337void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004338 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004339 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004340 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004341 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004342 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4343 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004344 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4345 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4346 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4347 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4348 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004349 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004350 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4351 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004352 i, args.pointerProperties[i].id,
4353 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4354 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4355 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4356 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4357 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4358 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4359 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4360 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4361 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4362 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004365
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004366 Result<void> motionCheck =
4367 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4368 args.pointerProperties.data());
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004369 if (!motionCheck.ok()) {
4370 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004371 return;
4372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004374 if (DEBUG_VERIFY_EVENTS) {
4375 auto [it, _] =
4376 mVerifiersByDisplay.try_emplace(args.displayId,
4377 StringPrintf("display %" PRId32, args.displayId));
4378 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004379 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4380 args.pointerProperties.data(), args.pointerCoords.data(),
4381 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004382 if (!result.ok()) {
4383 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4384 }
4385 }
4386
Prabir Pradhan678438e2023-04-13 19:32:51 +00004387 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004389
4390 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004391 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004392 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4393 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Antonio Kantekf16f2832021-09-28 04:39:20 +00004397 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 { // acquire lock
4399 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004400 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4401 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4402 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004403 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004404 if (touchStateIt != mTouchStatesByDisplay.end()) {
4405 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004406 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004407 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4408 }
4409 }
4410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411
4412 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004413 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004414 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004415 displayTransform = it->second.transform;
4416 }
4417
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 mLock.unlock();
4419
4420 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004421 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4422 args.action, args.actionButton, args.flags, args.edgeFlags,
4423 args.metaState, args.buttonState, args.classification,
4424 displayTransform, args.xPrecision, args.yPrecision,
4425 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004426 args.downTime, args.eventTime, args.getPointerCount(),
4427 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
4429 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004430 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 return; // event was consumed by the filter
4432 }
4433
4434 mLock.lock();
4435 }
4436
4437 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004438 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004439 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4440 args.displayId, policyFlags, args.action,
4441 args.actionButton, args.flags, args.metaState,
4442 args.buttonState, args.classification, args.edgeFlags,
4443 args.xPrecision, args.yPrecision,
4444 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004445 args.downTime, args.getPointerCount(),
4446 args.pointerProperties.data(),
4447 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448
Prabir Pradhan678438e2023-04-13 19:32:51 +00004449 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4450 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004451 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004452 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4453 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004454 }
4455
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004456 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 mLock.unlock();
4458 } // release lock
4459
4460 if (needWake) {
4461 mLooper->wake();
4462 }
4463}
4464
Prabir Pradhan678438e2023-04-13 19:32:51 +00004465void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004466 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004467 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4468 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004469 args.id, args.eventTime, args.deviceId, args.source,
4470 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004471 }
Chris Yef59a2f42020-10-16 12:55:26 -07004472
Antonio Kantekf16f2832021-09-28 04:39:20 +00004473 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004474 { // acquire lock
4475 mLock.lock();
4476
4477 // Just enqueue a new sensor event.
4478 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004479 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4480 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4481 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004482
4483 needWake = enqueueInboundEventLocked(std::move(newEntry));
4484 mLock.unlock();
4485 } // release lock
4486
4487 if (needWake) {
4488 mLooper->wake();
4489 }
4490}
4491
Prabir Pradhan678438e2023-04-13 19:32:51 +00004492void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004493 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004494 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4495 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004496 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004497 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004498}
4499
Prabir Pradhan678438e2023-04-13 19:32:51 +00004500bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004501 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502}
4503
Prabir Pradhan678438e2023-04-13 19:32:51 +00004504void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004505 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004506 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4507 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004508 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
Prabir Pradhan678438e2023-04-13 19:32:51 +00004511 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004513 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514}
4515
Prabir Pradhan678438e2023-04-13 19:32:51 +00004516void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004517 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004518 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4519 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521
Antonio Kantekf16f2832021-09-28 04:39:20 +00004522 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004524 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004526 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004527 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004528 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 } // release lock
4530
4531 if (needWake) {
4532 mLooper->wake();
4533 }
4534}
4535
Prabir Pradhan678438e2023-04-13 19:32:51 +00004536void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004537 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004538 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4539 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004540 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004541
Antonio Kantekf16f2832021-09-28 04:39:20 +00004542 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004543 { // acquire lock
4544 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004545 auto entry =
4546 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004547 needWake = enqueueInboundEventLocked(std::move(entry));
4548 } // release lock
4549
4550 if (needWake) {
4551 mLooper->wake();
4552 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004553}
4554
Prabir Pradhan5735a322022-04-11 17:23:34 +00004555InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004556 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004557 InputEventInjectionSync syncMode,
4558 std::chrono::milliseconds timeout,
4559 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004560 Result<void> eventValidation = validateInputEvent(*event);
4561 if (!eventValidation.ok()) {
4562 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4563 return InputEventInjectionResult::FAILED;
4564 }
4565
Prabir Pradhan65613802023-02-22 23:36:58 +00004566 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004567 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004568 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4569 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4570 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004571 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004572 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573
Prabir Pradhan5735a322022-04-11 17:23:34 +00004574 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004576 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004577 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4578 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4579 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4580 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4581 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004582 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004583 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004584 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004585 }
4586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004587 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004589 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004590 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004591 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004592 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004593 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4594 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4595 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004596 int32_t keyCode = incomingKey.getKeyCode();
4597 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004598 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004599 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004600 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004601 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004602 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4603 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4604 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4607 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004608 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004609
4610 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4611 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004612 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004613 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4614 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4615 std::to_string(t.duration().count()).c_str());
4616 }
4617 }
4618
4619 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004620 std::unique_ptr<KeyEntry> injectedEntry =
4621 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004622 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004623 incomingKey.getDisplayId(), policyFlags, action,
4624 flags, keyCode, incomingKey.getScanCode(), metaState,
4625 incomingKey.getRepeatCount(),
4626 incomingKey.getDownTime());
4627 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004628 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 }
4630
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004631 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004632 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004633 const bool isPointerEvent =
4634 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4635 // If a pointer event has no displayId specified, inject it to the default display.
4636 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4637 ? ADISPLAY_ID_DEFAULT
4638 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004639 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640
4641 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004642 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004643 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004644 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004645 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4646 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4647 std::to_string(t.duration().count()).c_str());
4648 }
4649 }
4650
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004651 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4652 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4653 }
4654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004655 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004656 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4657 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004659 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4660 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004661 displayId, policyFlags, motionEvent.getAction(),
4662 motionEvent.getActionButton(), flags,
4663 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004664 motionEvent.getButtonState(),
4665 motionEvent.getClassification(),
4666 motionEvent.getEdgeFlags(),
4667 motionEvent.getXPrecision(),
4668 motionEvent.getYPrecision(),
4669 motionEvent.getRawXCursorPosition(),
4670 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004671 motionEvent.getDownTime(),
4672 motionEvent.getPointerCount(),
4673 motionEvent.getPointerProperties(),
4674 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004675 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004676 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004677 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004678 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004679 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004680 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004681 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4682 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004683 displayId, policyFlags,
4684 motionEvent.getAction(),
4685 motionEvent.getActionButton(), flags,
4686 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004687 motionEvent.getButtonState(),
4688 motionEvent.getClassification(),
4689 motionEvent.getEdgeFlags(),
4690 motionEvent.getXPrecision(),
4691 motionEvent.getYPrecision(),
4692 motionEvent.getRawXCursorPosition(),
4693 motionEvent.getRawYCursorPosition(),
4694 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004695 motionEvent.getPointerCount(),
4696 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004697 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004698 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4699 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004700 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004701 }
4702 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004705 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004706 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 }
4709
Prabir Pradhan5735a322022-04-11 17:23:34 +00004710 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004711 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 injectionState->injectionIsAsync = true;
4713 }
4714
4715 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004716 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717
4718 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004719 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004720 if (DEBUG_INJECTION) {
4721 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4722 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004723 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004724 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 }
4726
4727 mLock.unlock();
4728
4729 if (needWake) {
4730 mLooper->wake();
4731 }
4732
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004733 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004735 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004737 if (syncMode == InputEventInjectionSync::NONE) {
4738 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 } else {
4740 for (;;) {
4741 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004742 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 break;
4744 }
4745
4746 nsecs_t remainingTimeout = endTime - now();
4747 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004748 if (DEBUG_INJECTION) {
4749 ALOGD("injectInputEvent - Timed out waiting for injection result "
4750 "to become available.");
4751 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004752 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 break;
4754 }
4755
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004756 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 }
4758
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004759 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4760 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004762 if (DEBUG_INJECTION) {
4763 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4764 injectionState->pendingForegroundDispatches);
4765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 nsecs_t remainingTimeout = endTime - now();
4767 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004768 if (DEBUG_INJECTION) {
4769 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4770 "dispatches to finish.");
4771 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004772 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 break;
4774 }
4775
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004776 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 }
4778 }
4779 }
4780
4781 injectionState->release();
4782 } // release lock
4783
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004784 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004785 LOG(DEBUG) << "injectInputEvent - Finished with result "
4786 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788
4789 return injectionResult;
4790}
4791
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004792std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004793 std::array<uint8_t, 32> calculatedHmac;
4794 std::unique_ptr<VerifiedInputEvent> result;
4795 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004796 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004797 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4798 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4799 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004800 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004801 break;
4802 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004803 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004804 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4805 VerifiedMotionEvent verifiedMotionEvent =
4806 verifiedMotionEventFromMotionEvent(motionEvent);
4807 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004808 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004809 break;
4810 }
4811 default: {
4812 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4813 return nullptr;
4814 }
4815 }
4816 if (calculatedHmac == INVALID_HMAC) {
4817 return nullptr;
4818 }
tyiu1573a672023-02-21 22:38:32 +00004819 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004820 return nullptr;
4821 }
4822 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004823}
4824
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004825void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004826 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004827 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004829 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004830 LOG(DEBUG) << "Setting input event injection result to "
4831 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004834 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 // Log the outcome since the injector did not wait for the injection result.
4836 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004837 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004838 ALOGV("Asynchronous input event injection succeeded.");
4839 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004840 case InputEventInjectionResult::TARGET_MISMATCH:
4841 ALOGV("Asynchronous input event injection target mismatch.");
4842 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004843 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 ALOGW("Asynchronous input event injection failed.");
4845 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 ALOGW("Asynchronous input event injection timed out.");
4848 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 case InputEventInjectionResult::PENDING:
4850 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4851 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 }
4853 }
4854
4855 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004856 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858}
4859
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004860void InputDispatcher::transformMotionEntryForInjectionLocked(
4861 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004862 // Input injection works in the logical display coordinate space, but the input pipeline works
4863 // display space, so we need to transform the injected events accordingly.
4864 const auto it = mDisplayInfos.find(entry.displayId);
4865 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004866 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004867
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004868 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4869 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4870 const vec2 cursor =
4871 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4872 {entry.xCursorPosition, entry.yCursorPosition});
4873 entry.xCursorPosition = cursor.x;
4874 entry.yCursorPosition = cursor.y;
4875 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004876 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004877 entry.pointerCoords[i] =
4878 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4879 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004880 }
4881}
4882
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004883void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4884 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 if (injectionState) {
4886 injectionState->pendingForegroundDispatches += 1;
4887 }
4888}
4889
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004890void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4891 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 if (injectionState) {
4893 injectionState->pendingForegroundDispatches -= 1;
4894
4895 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004896 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 }
4898 }
4899}
4900
chaviw98318de2021-05-19 16:45:23 -05004901const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004902 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004903 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004904 auto it = mWindowHandlesByDisplay.find(displayId);
4905 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004906}
4907
chaviw98318de2021-05-19 16:45:23 -05004908sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004909 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004910 if (windowHandleToken == nullptr) {
4911 return nullptr;
4912 }
4913
Arthur Hungb92218b2018-08-14 12:00:21 +08004914 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004915 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4916 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004917 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004918 return windowHandle;
4919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 }
4921 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004922 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923}
4924
chaviw98318de2021-05-19 16:45:23 -05004925sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4926 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004927 if (windowHandleToken == nullptr) {
4928 return nullptr;
4929 }
4930
chaviw98318de2021-05-19 16:45:23 -05004931 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004932 if (windowHandle->getToken() == windowHandleToken) {
4933 return windowHandle;
4934 }
4935 }
4936 return nullptr;
4937}
4938
chaviw98318de2021-05-19 16:45:23 -05004939sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4940 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004941 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004942 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4943 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004944 if (handle->getId() == windowHandle->getId() &&
4945 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004946 if (windowHandle->getInfo()->displayId != it.first) {
4947 ALOGE("Found window %s in display %" PRId32
4948 ", but it should belong to display %" PRId32,
4949 windowHandle->getName().c_str(), it.first,
4950 windowHandle->getInfo()->displayId);
4951 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004952 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 }
4955 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004956 return nullptr;
4957}
4958
chaviw98318de2021-05-19 16:45:23 -05004959sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004960 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4961 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962}
4963
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004964ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4965 auto displayInfoIt = mDisplayInfos.find(displayId);
4966 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4967 : kIdentityTransform;
4968}
4969
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004970bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4971 const MotionEntry& motionEntry) const {
4972 const WindowInfo& info = *window->getInfo();
4973
4974 // Skip spy window targets that are not valid for targeted injection.
4975 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004976 return false;
4977 }
4978
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004979 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4980 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4981 return false;
4982 }
4983
4984 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4985 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4986 window->getName().c_str());
4987 return false;
4988 }
4989
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004990 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004991 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004992 ALOGW("Not sending touch to %s because there's no corresponding connection",
4993 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004994 return false;
4995 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004996
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004997 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004998 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004999 return false;
5000 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005001
5002 // Drop events that can't be trusted due to occlusion
5003 const auto [x, y] = resolveTouchedPosition(motionEntry);
5004 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5005 if (!isTouchTrustedLocked(occlusionInfo)) {
5006 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005007 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005008 for (const auto& log : occlusionInfo.debugInfo) {
5009 ALOGD("%s", log.c_str());
5010 }
5011 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005012 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5013 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005014 return false;
5015 }
5016
5017 // Drop touch events if requested by input feature
5018 if (shouldDropInput(motionEntry, window)) {
5019 return false;
5020 }
5021
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005022 return true;
5023}
5024
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005025std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5026 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005027 auto connectionIt = mConnectionsByToken.find(token);
5028 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005029 return nullptr;
5030 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005031 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005032}
5033
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005034void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005035 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5036 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005037 // Remove all handles on a display if there are no windows left.
5038 mWindowHandlesByDisplay.erase(displayId);
5039 return;
5040 }
5041
5042 // Since we compare the pointer of input window handles across window updates, we need
5043 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005044 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5045 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5046 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005047 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005048 }
5049
chaviw98318de2021-05-19 16:45:23 -05005050 std::vector<sp<WindowInfoHandle>> newHandles;
5051 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005052 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005053 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005054 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005055 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005056 const bool canReceiveInput =
5057 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5058 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005059 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005060 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005061 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005062 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005063 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005064 }
5065
5066 if (info->displayId != displayId) {
5067 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5068 handle->getName().c_str(), displayId, info->displayId);
5069 continue;
5070 }
5071
Robert Carredd13602020-04-13 17:24:34 -07005072 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5073 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005074 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005075 oldHandle->updateFrom(handle);
5076 newHandles.push_back(oldHandle);
5077 } else {
5078 newHandles.push_back(handle);
5079 }
5080 }
5081
5082 // Insert or replace
5083 mWindowHandlesByDisplay[displayId] = newHandles;
5084}
5085
Arthur Hung72d8dc32020-03-28 00:48:39 +00005086void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005087 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005088 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005089 { // acquire lock
5090 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005091 for (const auto& [displayId, handles] : handlesPerDisplay) {
5092 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005093 }
5094 }
5095 // Wake up poll loop since it may need to make new input dispatching choices.
5096 mLooper->wake();
5097}
5098
Arthur Hungb92218b2018-08-14 12:00:21 +08005099/**
5100 * Called from InputManagerService, update window handle list by displayId that can receive input.
5101 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5102 * If set an empty list, remove all handles from the specific display.
5103 * For focused handle, check if need to change and send a cancel event to previous one.
5104 * For removed handle, check if need to send a cancel event if already in touch.
5105 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005106void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005107 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005108 if (DEBUG_FOCUS) {
5109 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005110 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005111 windowList += iwh->getName() + " ";
5112 }
5113 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115
Prabir Pradhand65552b2021-10-07 11:23:50 -07005116 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005117 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005118 const WindowInfo& info = *window->getInfo();
5119
5120 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005121 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005122 if (noInputWindow && window->getToken() != nullptr) {
5123 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5124 window->getName().c_str());
5125 window->releaseChannel();
5126 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005127
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005128 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005129 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5130 !info.inputConfig.test(
5131 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005132 "%s has feature SPY, but is not a trusted overlay.",
5133 window->getName().c_str());
5134
Prabir Pradhand65552b2021-10-07 11:23:50 -07005135 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005136 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5137 !info.inputConfig.test(
5138 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005139 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5140 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141 }
5142
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005144 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005146 // Save the old windows' orientation by ID before it gets updated.
5147 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005148 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005149 oldWindowOrientations.emplace(handle->getId(),
5150 handle->getInfo()->transform.getOrientation());
5151 }
5152
chaviw98318de2021-05-19 16:45:23 -05005153 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005154
chaviw98318de2021-05-19 16:45:23 -05005155 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005156
Vishnu Nairc519ff72021-01-21 08:23:08 -08005157 std::optional<FocusResolver::FocusChanges> changes =
5158 mFocusResolver.setInputWindows(displayId, windowHandles);
5159 if (changes) {
5160 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005163 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5164 mTouchStatesByDisplay.find(displayId);
5165 if (stateIt != mTouchStatesByDisplay.end()) {
5166 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005167 for (size_t i = 0; i < state.windows.size();) {
5168 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005169 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005170 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005171 ALOGD("Touched window was removed: %s in display %" PRId32,
5172 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005173 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005174 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005175 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5176 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005177 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005178 "touched window was removed");
5179 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005180 // Since we are about to drop the touch, cancel the events for the wallpaper as
5181 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005182 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005183 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5184 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005185 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005186 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005189 state.windows.erase(state.windows.begin() + i);
5190 } else {
5191 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 }
5193 }
arthurhungb89ccb02020-12-30 16:19:01 +08005194
arthurhung6d4bed92021-03-17 11:59:33 +08005195 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005196 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005197 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005198 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005199 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005200 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5201 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005202 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005203 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005204 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005205
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005206 // Determine if the orientation of any of the input windows have changed, and cancel all
5207 // pointer events if necessary.
5208 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5209 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5210 if (newWindowHandle != nullptr &&
5211 newWindowHandle->getInfo()->transform.getOrientation() !=
5212 oldWindowOrientations[oldWindowHandle->getId()]) {
5213 std::shared_ptr<InputChannel> inputChannel =
5214 getInputChannelLocked(newWindowHandle->getToken());
5215 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005216 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005217 "touched window's orientation changed");
5218 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005219 }
5220 }
5221 }
5222
Arthur Hung72d8dc32020-03-28 00:48:39 +00005223 // Release information for windows that are no longer present.
5224 // This ensures that unused input channels are released promptly.
5225 // Otherwise, they might stick around until the window handle is destroyed
5226 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005227 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005228 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005229 if (DEBUG_FOCUS) {
5230 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005231 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005232 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005233 }
chaviw291d88a2019-02-14 10:33:58 -08005234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235}
5236
5237void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005238 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005239 if (DEBUG_FOCUS) {
5240 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5241 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5242 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005243 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005244 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005245 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 } // release lock
5247
5248 // Wake up poll loop since it may need to make new input dispatching choices.
5249 mLooper->wake();
5250}
5251
Vishnu Nair599f1412021-06-21 10:39:58 -07005252void InputDispatcher::setFocusedApplicationLocked(
5253 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5254 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5255 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5256
5257 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5258 return; // This application is already focused. No need to wake up or change anything.
5259 }
5260
5261 // Set the new application handle.
5262 if (inputApplicationHandle != nullptr) {
5263 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5264 } else {
5265 mFocusedApplicationHandlesByDisplay.erase(displayId);
5266 }
5267
5268 // No matter what the old focused application was, stop waiting on it because it is
5269 // no longer focused.
5270 resetNoFocusedWindowTimeoutLocked();
5271}
5272
Tiger Huang721e26f2018-07-24 22:26:19 +08005273/**
5274 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5275 * the display not specified.
5276 *
5277 * We track any unreleased events for each window. If a window loses the ability to receive the
5278 * released event, we will send a cancel event to it. So when the focused display is changed, we
5279 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5280 * display. The display-specified events won't be affected.
5281 */
5282void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005283 if (DEBUG_FOCUS) {
5284 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5285 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005286 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005287 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005288
5289 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005290 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005291 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005292 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005293 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005294 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005295 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005297 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005298 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005299 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005300 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5301 }
5302 }
5303 mFocusedDisplayId = displayId;
5304
Chris Ye3c2d6f52020-08-09 10:39:48 -07005305 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005306 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005307 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005308
Vishnu Nairad321cd2020-08-20 16:40:21 -07005309 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005310 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005311 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005312 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005313 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005314 }
5315 }
5316 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005317 } // release lock
5318
5319 // Wake up poll loop since it may need to make new input dispatching choices.
5320 mLooper->wake();
5321}
5322
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005324 if (DEBUG_FOCUS) {
5325 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327
5328 bool changed;
5329 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005330 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331
5332 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5333 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005334 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336
5337 if (mDispatchEnabled && !enabled) {
5338 resetAndDropEverythingLocked("dispatcher is being disabled");
5339 }
5340
5341 mDispatchEnabled = enabled;
5342 mDispatchFrozen = frozen;
5343 changed = true;
5344 } else {
5345 changed = false;
5346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 } // release lock
5348
5349 if (changed) {
5350 // Wake up poll loop since it may need to make new input dispatching choices.
5351 mLooper->wake();
5352 }
5353}
5354
5355void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005356 if (DEBUG_FOCUS) {
5357 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359
5360 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005361 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362
5363 if (mInputFilterEnabled == enabled) {
5364 return;
5365 }
5366
5367 mInputFilterEnabled = enabled;
5368 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5369 } // release lock
5370
5371 // Wake up poll loop since there might be work to do to drop everything.
5372 mLooper->wake();
5373}
5374
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005375bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005376 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005377 bool needWake = false;
5378 {
5379 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005380 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005381 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005382 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005383 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5384 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005385 mTouchModePerDisplay.count(displayId) == 0
5386 ? "not set"
5387 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5388
Antonio Kantek15beb512022-06-13 22:35:41 +00005389 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5390 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005391 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005392 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005393 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005394 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5395 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005396 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005397 "window nor none of the previously interacted window",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005398 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005399 return false;
5400 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005401 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005402 mTouchModePerDisplay[displayId] = inTouchMode;
5403 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5404 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005405 needWake = enqueueInboundEventLocked(std::move(entry));
5406 } // release lock
5407
5408 if (needWake) {
5409 mLooper->wake();
5410 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005411 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005412}
5413
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005414bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005415 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5416 if (focusedToken == nullptr) {
5417 return false;
5418 }
5419 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5420 return isWindowOwnedBy(windowHandle, pid, uid);
5421}
5422
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005423bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005424 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5425 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5426 const sp<WindowInfoHandle> windowHandle =
5427 getWindowHandleLocked(connectionToken);
5428 return isWindowOwnedBy(windowHandle, pid, uid);
5429 }) != mInteractionConnectionTokens.end();
5430}
5431
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005432void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5433 if (opacity < 0 || opacity > 1) {
5434 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5435 return;
5436 }
5437
5438 std::scoped_lock lock(mLock);
5439 mMaximumObscuringOpacityForTouch = opacity;
5440}
5441
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005442std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5443InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005444 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5445 for (TouchedWindow& w : state.windows) {
5446 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005447 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005448 }
5449 }
5450 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005451 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452}
5453
arthurhungb89ccb02020-12-30 16:19:01 +08005454bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5455 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005456 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005457 if (DEBUG_FOCUS) {
5458 ALOGD("Trivial transfer to same window.");
5459 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005460 return true;
5461 }
5462
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005464 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465
Arthur Hungabbb9d82021-09-01 14:52:30 +00005466 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005467 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005468
Arthur Hungabbb9d82021-09-01 14:52:30 +00005469 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005470 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 return false;
5472 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005473 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5474 if (deviceIds.size() != 1) {
5475 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5476 << " for window: " << touchedWindow->dump();
5477 return false;
5478 }
5479 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005480
Arthur Hungabbb9d82021-09-01 14:52:30 +00005481 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5482 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005483 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005484 return false;
5485 }
5486
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005487 if (DEBUG_FOCUS) {
5488 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005489 touchedWindow->windowHandle->getName().c_str(),
5490 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 }
5492
Arthur Hungabbb9d82021-09-01 14:52:30 +00005493 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005494 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005495 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005496 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005497 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498
Arthur Hungabbb9d82021-09-01 14:52:30 +00005499 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005500 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005501 ftl::Flags<InputTarget::Flags> newTargetFlags =
5502 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005503 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005504 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005505 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005506 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5507 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508
Arthur Hungabbb9d82021-09-01 14:52:30 +00005509 // Store the dragging window.
5510 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005511 if (pointerIds.count() != 1) {
5512 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5513 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005514 return false;
5515 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005516 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005517 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005518 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 }
5520
Arthur Hungabbb9d82021-09-01 14:52:30 +00005521 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005522 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5523 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005524 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005525 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005526 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5527 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005529 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5530 newTargetFlags);
5531
5532 // Check if the wallpaper window should deliver the corresponding event.
5533 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005534 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 } // release lock
5537
5538 // Wake up poll loop since it may need to make new input dispatching choices.
5539 mLooper->wake();
5540 return true;
5541}
5542
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005543/**
5544 * Get the touched foreground window on the given display.
5545 * Return null if there are no windows touched on that display, or if more than one foreground
5546 * window is being touched.
5547 */
5548sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5549 auto stateIt = mTouchStatesByDisplay.find(displayId);
5550 if (stateIt == mTouchStatesByDisplay.end()) {
5551 ALOGI("No touch state on display %" PRId32, displayId);
5552 return nullptr;
5553 }
5554
5555 const TouchState& state = stateIt->second;
5556 sp<WindowInfoHandle> touchedForegroundWindow;
5557 // If multiple foreground windows are touched, return nullptr
5558 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005559 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005560 if (touchedForegroundWindow != nullptr) {
5561 ALOGI("Two or more foreground windows: %s and %s",
5562 touchedForegroundWindow->getName().c_str(),
5563 window.windowHandle->getName().c_str());
5564 return nullptr;
5565 }
5566 touchedForegroundWindow = window.windowHandle;
5567 }
5568 }
5569 return touchedForegroundWindow;
5570}
5571
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005572// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005573bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005574 sp<IBinder> fromToken;
5575 { // acquire lock
5576 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005577 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005578 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005579 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5580 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005581 return false;
5582 }
5583
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005584 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5585 if (from == nullptr) {
5586 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5587 return false;
5588 }
5589
5590 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005591 } // release lock
5592
5593 return transferTouchFocus(fromToken, destChannelToken);
5594}
5595
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005597 if (DEBUG_FOCUS) {
5598 ALOGD("Resetting and dropping all events (%s).", reason);
5599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600
Michael Wrightfb04fd52022-11-24 22:31:11 +00005601 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 synthesizeCancelationEventsForAllConnectionsLocked(options);
5603
5604 resetKeyRepeatLocked();
5605 releasePendingEventLocked();
5606 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005607 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005609 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005610 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005611 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612}
5613
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005614void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005615 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 dumpDispatchStateLocked(dump);
5617
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005618 std::istringstream stream(dump);
5619 std::string line;
5620
5621 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005622 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 }
5624}
5625
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005626std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005627 std::string dump;
5628
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005629 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5630 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005631
5632 std::string windowName = "None";
5633 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005634 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005635 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5636 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5637 : "token has capture without window";
5638 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005639 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005640
5641 return dump;
5642}
5643
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005644void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005645 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5646 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5647 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005648 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649
Tiger Huang721e26f2018-07-24 22:26:19 +08005650 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5651 dump += StringPrintf(INDENT "FocusedApplications:\n");
5652 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5653 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005654 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005655 const std::chrono::duration timeout =
5656 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005657 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005658 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005659 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005662 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005664
Vishnu Nairc519ff72021-01-21 08:23:08 -08005665 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005666 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005668 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005669 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005670 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005671 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5672 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673 }
5674 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005675 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 }
5677
arthurhung6d4bed92021-03-17 11:59:33 +08005678 if (mDragState) {
5679 dump += StringPrintf(INDENT "DragState:\n");
5680 mDragState->dump(dump, INDENT2);
5681 }
5682
Arthur Hungb92218b2018-08-14 12:00:21 +08005683 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005684 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5685 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5686 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5687 const auto& displayInfo = it->second;
5688 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5689 displayInfo.logicalHeight);
5690 displayInfo.transform.dump(dump, "transform", INDENT4);
5691 } else {
5692 dump += INDENT2 "No DisplayInfo found!\n";
5693 }
5694
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005695 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005696 dump += INDENT2 "Windows:\n";
5697 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005698 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5699 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005701 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005702 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005703 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005704 "applicationInfo.name=%s, "
5705 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005706 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005707 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005708 windowInfo->displayId,
5709 windowInfo->inputConfig.string().c_str(),
5710 windowInfo->alpha, windowInfo->frameLeft,
5711 windowInfo->frameTop, windowInfo->frameRight,
5712 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005713 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005714 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005715 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005716 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005717 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005718 "touchOcclusionMode=%s\n",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005719 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005720 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005721 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005722 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005723 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005724 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005725 }
5726 } else {
5727 dump += INDENT2 "Windows: <none>\n";
5728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
5730 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005731 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005734 if (!mGlobalMonitorsByDisplay.empty()) {
5735 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5736 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005737 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005740 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005743 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744
5745 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005746 if (!mRecentQueue.empty()) {
5747 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005748 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005749 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005750 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005751 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 }
5753 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005754 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755 }
5756
5757 // Dump event currently being dispatched.
5758 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005759 dump += INDENT "PendingEvent:\n";
5760 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005761 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005762 dump += StringPrintf(", age=%" PRId64 "ms\n",
5763 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005765 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
5767
5768 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005769 if (!mInboundQueue.empty()) {
5770 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005771 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005772 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005773 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005774 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 }
5776 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005777 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 }
5779
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005780 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005782 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005783 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005784 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005785 }
5786 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005787 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005788 }
5789
Prabir Pradhancef936d2021-07-21 16:17:52 +00005790 if (!mCommandQueue.empty()) {
5791 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5792 } else {
5793 dump += INDENT "CommandQueue: <empty>\n";
5794 }
5795
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005796 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005797 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005798 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005799 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005800 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005801 connection->inputChannel->getFd().get(),
5802 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005803 connection->getWindowName().c_str(),
5804 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005805 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005807 if (!connection->outboundQueue.empty()) {
5808 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5809 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005810 dump += dumpQueue(connection->outboundQueue, currentTime);
5811
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005813 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005816 if (!connection->waitQueue.empty()) {
5817 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5818 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005819 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005821 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822 }
5823 }
5824 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005825 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 }
5827
5828 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005829 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5830 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005832 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 }
5834
Antonio Kantek15beb512022-06-13 22:35:41 +00005835 if (!mTouchModePerDisplay.empty()) {
5836 dump += INDENT "TouchModePerDisplay:\n";
5837 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5838 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5839 std::to_string(touchMode).c_str());
5840 }
5841 } else {
5842 dump += INDENT "TouchModePerDisplay: <none>\n";
5843 }
5844
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005845 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005846 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5847 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5848 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005849 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005850 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851}
5852
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005853void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005854 const size_t numMonitors = monitors.size();
5855 for (size_t i = 0; i < numMonitors; i++) {
5856 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005857 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005858 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5859 dump += "\n";
5860 }
5861}
5862
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005863class LooperEventCallback : public LooperCallback {
5864public:
5865 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5866 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5867
5868private:
5869 std::function<int(int events)> mCallback;
5870};
5871
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005872Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005873 if (DEBUG_CHANNEL_CREATION) {
5874 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005877 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005878 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005879 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005880
5881 if (result) {
5882 return base::Error(result) << "Failed to open input channel pair with name " << name;
5883 }
5884
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005886 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005887 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005888 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005889 std::shared_ptr<Connection> connection =
5890 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5891 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005893 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5894 ALOGE("Created a new connection, but the token %p is already known", token.get());
5895 }
5896 mConnectionsByToken.emplace(token, connection);
5897
5898 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5899 this, std::placeholders::_1, token);
5900
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005901 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5902 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903 } // release lock
5904
5905 // Wake the looper because some connections have changed.
5906 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005907 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908}
5909
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005910Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005911 const std::string& name,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005912 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005913 std::shared_ptr<InputChannel> serverChannel;
5914 std::unique_ptr<InputChannel> clientChannel;
5915 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5916 if (result) {
5917 return base::Error(result) << "Failed to open input channel pair with name " << name;
5918 }
5919
Michael Wright3dd60e22019-03-27 22:06:44 +00005920 { // acquire lock
5921 std::scoped_lock _l(mLock);
5922
5923 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005924 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5925 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005926 }
5927
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005928 std::shared_ptr<Connection> connection =
5929 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005930 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005931 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005932
5933 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5934 ALOGE("Created a new connection, but the token %p is already known", token.get());
5935 }
5936 mConnectionsByToken.emplace(token, connection);
5937 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5938 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005939
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005940 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005941
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005942 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5943 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005944 }
Garfield Tan15601662020-09-22 15:32:38 -07005945
Michael Wright3dd60e22019-03-27 22:06:44 +00005946 // Wake the looper because some connections have changed.
5947 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005948 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005949}
5950
Garfield Tan15601662020-09-22 15:32:38 -07005951status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005953 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954
Harry Cutts33476232023-01-30 19:57:29 +00005955 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 if (status) {
5957 return status;
5958 }
5959 } // release lock
5960
5961 // Wake the poll loop because removing the connection may have changed the current
5962 // synchronization state.
5963 mLooper->wake();
5964 return OK;
5965}
5966
Garfield Tan15601662020-09-22 15:32:38 -07005967status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5968 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005969 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005970 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005971 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 return BAD_VALUE;
5973 }
5974
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005975 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005976
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005978 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 }
5980
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005981 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982
5983 nsecs_t currentTime = now();
5984 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5985
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005986 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987 return OK;
5988}
5989
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005990void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005991 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5992 auto& [displayId, monitors] = *it;
5993 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5994 return monitor.inputChannel->getConnectionToken() == connectionToken;
5995 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005996
Michael Wright3dd60e22019-03-27 22:06:44 +00005997 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005998 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005999 } else {
6000 ++it;
6001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002 }
6003}
6004
Michael Wright3dd60e22019-03-27 22:06:44 +00006005status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006006 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006007 return pilferPointersLocked(token);
6008}
Michael Wright3dd60e22019-03-27 22:06:44 +00006009
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006010status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006011 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6012 if (!requestingChannel) {
6013 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
6014 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006015 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006016
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006017 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006018 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006019 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
6020 " Ignoring.");
6021 return BAD_VALUE;
6022 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006023 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
6024 if (deviceIds.size() != 1) {
6025 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
6026 << " in window: " << windowPtr->dump();
6027 return BAD_VALUE;
6028 }
6029 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006030
6031 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006032 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006033 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00006034 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006035 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006036 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006037 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006038 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6039 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006040 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006041 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006042 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006043 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006044 if (channel != nullptr && channel->getConnectionToken() != token) {
6045 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6046 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6047 canceledWindows += channel->getName();
6048 }
6049 }
6050 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6051 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6052 canceledWindows.c_str());
6053
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006054 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006055 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006056 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006057
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006058 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006059 return OK;
6060}
6061
Prabir Pradhan99987712020-11-10 18:43:05 -08006062void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6063 { // acquire lock
6064 std::scoped_lock _l(mLock);
6065 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006066 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006067 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6068 windowHandle != nullptr ? windowHandle->getName().c_str()
6069 : "token without window");
6070 }
6071
Vishnu Nairc519ff72021-01-21 08:23:08 -08006072 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006073 if (focusedToken != windowToken) {
6074 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6075 enabled ? "enable" : "disable");
6076 return;
6077 }
6078
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006079 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006080 ALOGW("Ignoring request to %s Pointer Capture: "
6081 "window has %s requested pointer capture.",
6082 enabled ? "enable" : "disable", enabled ? "already" : "not");
6083 return;
6084 }
6085
Christine Franksb768bb42021-11-29 12:11:31 -08006086 if (enabled) {
6087 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6088 mIneligibleDisplaysForPointerCapture.end(),
6089 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6090 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6091 return;
6092 }
6093 }
6094
Prabir Pradhan99987712020-11-10 18:43:05 -08006095 setPointerCaptureLocked(enabled);
6096 } // release lock
6097
6098 // Wake the thread to process command entries.
6099 mLooper->wake();
6100}
6101
Christine Franksb768bb42021-11-29 12:11:31 -08006102void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6103 { // acquire lock
6104 std::scoped_lock _l(mLock);
6105 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6106 if (!isEligible) {
6107 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6108 }
6109 } // release lock
6110}
6111
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006112std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006113 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006114 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006115 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006116 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006117 }
6118 }
6119 }
6120 return std::nullopt;
6121}
6122
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006123std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6124 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006125 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006126 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006127 }
6128
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006129 for (const auto& [token, connection] : mConnectionsByToken) {
6130 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006131 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006132 }
6133 }
Robert Carr4e670e52018-08-15 13:26:12 -07006134
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006135 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136}
6137
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006138std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006139 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006140 if (connection == nullptr) {
6141 return "<nullptr>";
6142 }
6143 return connection->getInputChannelName();
6144}
6145
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006146void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006147 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006148 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006149}
6150
Prabir Pradhancef936d2021-07-21 16:17:52 +00006151void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006152 const std::shared_ptr<Connection>& connection,
6153 uint32_t seq, bool handled,
6154 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006155 // Handle post-event policy actions.
6156 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6157 if (dispatchEntryIt == connection->waitQueue.end()) {
6158 return;
6159 }
6160 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6161 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6162 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6163 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6164 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6165 }
6166 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6167 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6168 connection->inputChannel->getConnectionToken(),
6169 dispatchEntry->deliveryTime, consumeTime, finishTime);
6170 }
6171
6172 bool restartEvent;
6173 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6174 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6175 restartEvent =
6176 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6177 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6178 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6179 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6180 handled);
6181 } else {
6182 restartEvent = false;
6183 }
6184
6185 // Dequeue the event and start the next cycle.
6186 // Because the lock might have been released, it is possible that the
6187 // contents of the wait queue to have been drained, so we need to double-check
6188 // a few things.
6189 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6190 if (dispatchEntryIt != connection->waitQueue.end()) {
6191 dispatchEntry = *dispatchEntryIt;
6192 connection->waitQueue.erase(dispatchEntryIt);
6193 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6194 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6195 if (!connection->responsive) {
6196 connection->responsive = isConnectionResponsive(*connection);
6197 if (connection->responsive) {
6198 // The connection was unresponsive, and now it's responsive.
6199 processConnectionResponsiveLocked(*connection);
6200 }
6201 }
6202 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006203 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006204 connection->outboundQueue.push_front(dispatchEntry);
6205 traceOutboundQueueLength(*connection);
6206 } else {
6207 releaseDispatchEntry(dispatchEntry);
6208 }
6209 }
6210
6211 // Start the next dispatch cycle for this connection.
6212 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213}
6214
Prabir Pradhancef936d2021-07-21 16:17:52 +00006215void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6216 const sp<IBinder>& newToken) {
6217 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6218 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006219 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006220 };
6221 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222}
6223
Prabir Pradhancef936d2021-07-21 16:17:52 +00006224void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6225 auto command = [this, token, x, y]() REQUIRES(mLock) {
6226 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006227 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006228 };
6229 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006230}
6231
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006232void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006233 if (connection == nullptr) {
6234 LOG_ALWAYS_FATAL("Caller must check for nullness");
6235 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006236 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6237 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006238 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006239 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006240 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006241 return;
6242 }
6243 /**
6244 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6245 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6246 * has changed. This could cause newer entries to time out before the already dispatched
6247 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6248 * processes the events linearly. So providing information about the oldest entry seems to be
6249 * most useful.
6250 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006251 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006252 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6253 std::string reason =
6254 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006255 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006256 ns2ms(currentWait),
6257 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006258 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006259 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006260
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006261 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6262
6263 // Stop waking up for events on this connection, it is already unresponsive
6264 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006265}
6266
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006267void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6268 std::string reason =
6269 StringPrintf("%s does not have a focused window", application->getName().c_str());
6270 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006271
Yabin Cui8eb9c552023-06-08 18:05:07 +00006272 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006273 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006274 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006275 };
6276 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006277}
6278
chaviw98318de2021-05-19 16:45:23 -05006279void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006280 const std::string& reason) {
6281 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6282 updateLastAnrStateLocked(windowLabel, reason);
6283}
6284
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006285void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6286 const std::string& reason) {
6287 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006288 updateLastAnrStateLocked(windowLabel, reason);
6289}
6290
6291void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6292 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006293 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006294 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 struct tm tm;
6296 localtime_r(&t, &tm);
6297 char timestr[64];
6298 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006299 mLastAnrState.clear();
6300 mLastAnrState += INDENT "ANR:\n";
6301 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006302 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6303 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006304 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305}
6306
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6308 KeyEntry& entry) {
6309 const KeyEvent event = createKeyEvent(entry);
6310 nsecs_t delay = 0;
6311 { // release lock
6312 scoped_unlock unlock(mLock);
6313 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006314 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6316 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6317 std::to_string(t.duration().count()).c_str());
6318 }
6319 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320
6321 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006322 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006323 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006324 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006325 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006326 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006327 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329}
6330
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006332 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006333 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006334 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006335 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006336 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006337 };
6338 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006339}
6340
Prabir Pradhanedd96402022-02-15 01:46:16 -08006341void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006342 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006343 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006344 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006345 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006346 };
6347 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348}
6349
6350/**
6351 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6352 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6353 * command entry to the command queue.
6354 */
6355void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6356 std::string reason) {
6357 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006358 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006359 if (connection.monitor) {
6360 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6361 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006362 pid = findMonitorPidByTokenLocked(connectionToken);
6363 } else {
6364 // The connection is a window
6365 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6366 reason.c_str());
6367 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6368 if (handle != nullptr) {
6369 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006370 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006371 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006372 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006373}
6374
6375/**
6376 * Tell the policy that a connection has become responsive so that it can stop ANR.
6377 */
6378void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6379 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006380 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006381 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006382 pid = findMonitorPidByTokenLocked(connectionToken);
6383 } else {
6384 // The connection is a window
6385 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6386 if (handle != nullptr) {
6387 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006388 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006389 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006390 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006391}
6392
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006393bool InputDispatcher::afterKeyEventLockedInterruptable(
6394 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6395 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006396 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006397 if (!handled) {
6398 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006399 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006400 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006401 return false;
6402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404 // Get the fallback key state.
6405 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006406 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006407 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006408 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006409 connection->inputState.removeFallbackKey(originalKeyCode);
6410 }
6411
6412 if (handled || !dispatchEntry->hasForegroundTarget()) {
6413 // If the application handles the original key for which we previously
6414 // generated a fallback or if the window is not a foreground window,
6415 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006416 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006418 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6419 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6420 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6421 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6422 keyEntry.policyFlags);
6423 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006424 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426
6427 mLock.unlock();
6428
Prabir Pradhana41d2442023-04-20 21:30:40 +00006429 if (const auto unhandledKeyFallback =
6430 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6431 event, keyEntry.policyFlags);
6432 unhandledKeyFallback) {
6433 event = *unhandledKeyFallback;
6434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435
6436 mLock.lock();
6437
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006438 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006439 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006440 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006441 "application handled the original non-fallback key "
6442 "or is no longer a foreground target, "
6443 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006445 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006447 connection->inputState.removeFallbackKey(originalKeyCode);
6448 }
6449 } else {
6450 // If the application did not handle a non-fallback key, first check
6451 // that we are in a good state to perform unhandled key event processing
6452 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006453 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006455 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6456 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6457 "since this is not an initial down. "
6458 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6459 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6460 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 return false;
6462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006465 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6466 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6467 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6468 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6469 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006470 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006471
6472 mLock.unlock();
6473
Prabir Pradhana41d2442023-04-20 21:30:40 +00006474 bool fallback = false;
6475 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6476 event, keyEntry.policyFlags);
6477 fb) {
6478 fallback = true;
6479 event = *fb;
6480 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006481
6482 mLock.lock();
6483
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006484 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 connection->inputState.removeFallbackKey(originalKeyCode);
6486 return false;
6487 }
6488
6489 // Latch the fallback keycode for this key on an initial down.
6490 // The fallback keycode cannot change at any other point in the lifecycle.
6491 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006492 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006493 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006494 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006495 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006496 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 }
6499
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006500 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501
6502 // Cancel the fallback key if the policy decides not to send it anymore.
6503 // We will continue to dispatch the key to the policy but we will no
6504 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006505 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6506 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006507 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6508 if (fallback) {
6509 ALOGD("Unhandled key event: Policy requested to send key %d"
6510 "as a fallback for %d, but on the DOWN it had requested "
6511 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006512 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006513 } else {
6514 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6515 "but on the DOWN it had requested to send %d. "
6516 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006517 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006518 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006519 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006520
Michael Wrightfb04fd52022-11-24 22:31:11 +00006521 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006522 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006523 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 synthesizeCancelationEventsForConnectionLocked(connection, options);
6525
6526 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006527 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006528 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006529 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006530 }
6531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006533 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6534 {
6535 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006536 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006537 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006538 for (const auto& [key, value] : fallbackKeys) {
6539 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006540 }
6541 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6542 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006544 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006545
6546 if (fallback) {
6547 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006548 keyEntry.eventTime = event.getEventTime();
6549 keyEntry.deviceId = event.getDeviceId();
6550 keyEntry.source = event.getSource();
6551 keyEntry.displayId = event.getDisplayId();
6552 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006553 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006554 keyEntry.scanCode = event.getScanCode();
6555 keyEntry.metaState = event.getMetaState();
6556 keyEntry.repeatCount = event.getRepeatCount();
6557 keyEntry.downTime = event.getDownTime();
6558 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006559
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006560 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6561 ALOGD("Unhandled key event: Dispatching fallback key. "
6562 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006563 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006564 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006565 return true; // restart the event
6566 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006567 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6568 ALOGD("Unhandled key event: No fallback key.");
6569 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006570
6571 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006572 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 }
6574 }
6575 return false;
6576}
6577
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006578bool InputDispatcher::afterMotionEventLockedInterruptable(
6579 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6580 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581 return false;
6582}
6583
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584void InputDispatcher::traceInboundQueueLengthLocked() {
6585 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006586 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006587 }
6588}
6589
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006590void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591 if (ATRACE_ENABLED()) {
6592 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006593 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6594 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595 }
6596}
6597
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006598void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006599 if (ATRACE_ENABLED()) {
6600 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006601 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6602 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603 }
6604}
6605
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006606void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006607 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006609 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610 dumpDispatchStateLocked(dump);
6611
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006612 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006613 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006614 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 }
6616}
6617
6618void InputDispatcher::monitor() {
6619 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006620 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006621 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006622 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623}
6624
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006625/**
6626 * Wake up the dispatcher and wait until it processes all events and commands.
6627 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6628 * this method can be safely called from any thread, as long as you've ensured that
6629 * the work you are interested in completing has already been queued.
6630 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006631bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006632 /**
6633 * Timeout should represent the longest possible time that a device might spend processing
6634 * events and commands.
6635 */
6636 constexpr std::chrono::duration TIMEOUT = 100ms;
6637 std::unique_lock lock(mLock);
6638 mLooper->wake();
6639 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6640 return result == std::cv_status::no_timeout;
6641}
6642
Vishnu Naire798b472020-07-23 13:52:21 -07006643/**
6644 * Sets focus to the window identified by the token. This must be called
6645 * after updating any input window handles.
6646 *
6647 * Params:
6648 * request.token - input channel token used to identify the window that should gain focus.
6649 * request.focusedToken - the token that the caller expects currently to be focused. If the
6650 * specified token does not match the currently focused window, this request will be dropped.
6651 * If the specified focused token matches the currently focused window, the call will succeed.
6652 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6653 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6654 * when requesting the focus change. This determines which request gets
6655 * precedence if there is a focus change request from another source such as pointer down.
6656 */
Vishnu Nair958da932020-08-21 17:12:37 -07006657void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6658 { // acquire lock
6659 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006660 std::optional<FocusResolver::FocusChanges> changes =
6661 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6662 if (changes) {
6663 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006664 }
6665 } // release lock
6666 // Wake up poll loop since it may need to make new input dispatching choices.
6667 mLooper->wake();
6668}
6669
Vishnu Nairc519ff72021-01-21 08:23:08 -08006670void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6671 if (changes.oldFocus) {
6672 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006673 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006674 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006675 "focus left window");
6676 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006677 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006678 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006679 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006680 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006681 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006682 }
6683
Prabir Pradhan99987712020-11-10 18:43:05 -08006684 // If a window has pointer capture, then it must have focus. We need to ensure that this
6685 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6686 // If the window loses focus before it loses pointer capture, then the window can be in a state
6687 // where it has pointer capture but not focus, violating the contract. Therefore we must
6688 // dispatch the pointer capture event before the focus event. Since focus events are added to
6689 // the front of the queue (above), we add the pointer capture event to the front of the queue
6690 // after the focus events are added. This ensures the pointer capture event ends up at the
6691 // front.
6692 disablePointerCaptureForcedLocked();
6693
Vishnu Nairc519ff72021-01-21 08:23:08 -08006694 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006695 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006696 }
6697}
Vishnu Nair958da932020-08-21 17:12:37 -07006698
Prabir Pradhan99987712020-11-10 18:43:05 -08006699void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006700 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006701 return;
6702 }
6703
6704 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6705
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006706 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006707 setPointerCaptureLocked(false);
6708 }
6709
6710 if (!mWindowTokenWithPointerCapture) {
6711 // No need to send capture changes because no window has capture.
6712 return;
6713 }
6714
6715 if (mPendingEvent != nullptr) {
6716 // Move the pending event to the front of the queue. This will give the chance
6717 // for the pending event to be dropped if it is a captured event.
6718 mInboundQueue.push_front(mPendingEvent);
6719 mPendingEvent = nullptr;
6720 }
6721
6722 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006723 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006724 mInboundQueue.push_front(std::move(entry));
6725}
6726
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006727void InputDispatcher::setPointerCaptureLocked(bool enable) {
6728 mCurrentPointerCaptureRequest.enable = enable;
6729 mCurrentPointerCaptureRequest.seq++;
6730 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006731 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006732 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006733 };
6734 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006735}
6736
Vishnu Nair599f1412021-06-21 10:39:58 -07006737void InputDispatcher::displayRemoved(int32_t displayId) {
6738 { // acquire lock
6739 std::scoped_lock _l(mLock);
6740 // Set an empty list to remove all handles from the specific display.
6741 setInputWindowsLocked(/* window handles */ {}, displayId);
6742 setFocusedApplicationLocked(displayId, nullptr);
6743 // Call focus resolver to clean up stale requests. This must be called after input windows
6744 // have been removed for the removed display.
6745 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006746 // Reset pointer capture eligibility, regardless of previous state.
6747 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006748 // Remove the associated touch mode state.
6749 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006750 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006751 } // release lock
6752
6753 // Wake up poll loop since it may need to make new input dispatching choices.
6754 mLooper->wake();
6755}
6756
Patrick Williamsd828f302023-04-28 17:52:08 -05006757void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006758 // The listener sends the windows as a flattened array. Separate the windows by display for
6759 // more convenient parsing.
6760 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006761 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006762 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006763 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006764 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006765
6766 { // acquire lock
6767 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006768
6769 // Ensure that we have an entry created for all existing displays so that if a displayId has
6770 // no windows, we can tell that the windows were removed from the display.
6771 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6772 handlesPerDisplay[displayId];
6773 }
6774
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006775 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006776 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006777 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6778 }
6779
6780 for (const auto& [displayId, handles] : handlesPerDisplay) {
6781 setInputWindowsLocked(handles, displayId);
6782 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006783
6784 if (update.vsyncId < mWindowInfosVsyncId) {
6785 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6786 ", current update vsync id: %" PRId64,
6787 mWindowInfosVsyncId, update.vsyncId);
6788 }
6789 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006790 }
6791 // Wake up poll loop since it may need to make new input dispatching choices.
6792 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006793}
6794
Vishnu Nair062a8672021-09-03 16:07:44 -07006795bool InputDispatcher::shouldDropInput(
6796 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006797 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6798 (windowHandle->getInfo()->inputConfig.test(
6799 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006800 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006801 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6802 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006803 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006804 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006805 windowHandle->getInfo()->displayId);
6806 return true;
6807 }
6808 return false;
6809}
6810
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006811void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006812 const gui::WindowInfosUpdate& update) {
6813 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006814}
6815
Arthur Hungdfd528e2021-12-08 13:23:04 +00006816void InputDispatcher::cancelCurrentTouch() {
6817 {
6818 std::scoped_lock _l(mLock);
6819 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006820 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006821 "cancel current touch");
6822 synthesizeCancelationEventsForAllConnectionsLocked(options);
6823
6824 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006825 }
6826 // Wake up poll loop since there might be work to do.
6827 mLooper->wake();
6828}
6829
Prabir Pradhan87112a72023-04-20 19:13:39 +00006830void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006831 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006832
6833 std::scoped_lock _l(mLock);
6834 mConfig = config;
6835}
6836
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006837void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6838 std::scoped_lock _l(mLock);
6839 mMonitorDispatchingTimeout = timeout;
6840}
6841
Arthur Hungc539dbb2022-12-08 07:45:36 +00006842void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6843 const sp<WindowInfoHandle>& oldWindowHandle,
6844 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006845 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006846 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006847 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6848 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006849 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6850 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6851 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6852 newWindowHandle->getInfo()->inputConfig.test(
6853 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6854 const sp<WindowInfoHandle> oldWallpaper =
6855 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6856 const sp<WindowInfoHandle> newWallpaper =
6857 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6858 if (oldWallpaper == newWallpaper) {
6859 return;
6860 }
6861
6862 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006863 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6864 addWindowTargetLocked(oldWallpaper,
6865 oldTouchedWindow.targetFlags |
6866 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006867 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6868 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006869 }
6870
6871 if (newWallpaper != nullptr) {
6872 state.addOrUpdateWindow(newWallpaper,
6873 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6874 InputTarget::Flags::WINDOW_IS_OBSCURED |
6875 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006876 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006877 }
6878}
6879
6880void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6881 ftl::Flags<InputTarget::Flags> newTargetFlags,
6882 const sp<WindowInfoHandle> fromWindowHandle,
6883 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006884 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006885 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006886 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6887 fromWindowHandle->getInfo()->inputConfig.test(
6888 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6889 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6890 toWindowHandle->getInfo()->inputConfig.test(
6891 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6892
6893 const sp<WindowInfoHandle> oldWallpaper =
6894 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6895 const sp<WindowInfoHandle> newWallpaper =
6896 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6897 if (oldWallpaper == newWallpaper) {
6898 return;
6899 }
6900
6901 if (oldWallpaper != nullptr) {
6902 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6903 "transferring touch focus to another window");
6904 state.removeWindowByToken(oldWallpaper->getToken());
6905 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6906 }
6907
6908 if (newWallpaper != nullptr) {
6909 nsecs_t downTimeInTarget = now();
6910 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6911 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6912 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6913 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006914 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6915 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006916 std::shared_ptr<Connection> wallpaperConnection =
6917 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006918 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006919 std::shared_ptr<Connection> toConnection =
6920 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006921 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6922 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6923 wallpaperFlags);
6924 }
6925 }
6926}
6927
6928sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6929 const sp<WindowInfoHandle>& windowHandle) const {
6930 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6931 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6932 bool foundWindow = false;
6933 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6934 if (!foundWindow && otherHandle != windowHandle) {
6935 continue;
6936 }
6937 if (windowHandle == otherHandle) {
6938 foundWindow = true;
6939 continue;
6940 }
6941
6942 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6943 return otherHandle;
6944 }
6945 }
6946 return nullptr;
6947}
6948
Garfield Tane84e6f92019-08-29 17:28:41 -07006949} // namespace android::inputdispatcher