blob: 7981e9acb55a938f41a1ecfe59caa5fcb58f9c14 [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 Vishniakou6278ca22022-10-25 11:19:19 -07002083 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084
Tiger Huang721e26f2018-07-24 22:26:19 +08002085 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002086 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002087 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002088 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2089
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 // If there is no currently focused window and no focused application
2091 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2093 ALOGI("Dropping %s event because there is no focused window or focused application in "
2094 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002095 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002096 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 }
2098
Vishnu Nair062a8672021-09-03 16:07:44 -07002099 // Drop key events if requested by input feature
2100 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002101 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002102 }
2103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2105 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2106 // start interacting with another application via touch (app switch). This code can be removed
2107 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2108 // an app is expected to have a focused window.
2109 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2110 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2111 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002112 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2113 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2114 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002116 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 ALOGW("Waiting because no window has focus but %s may eventually add a "
2118 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002119 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002121 outInjectionResult = InputEventInjectionResult::PENDING;
2122 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002123 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2124 // Already raised ANR. Drop the event
2125 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002126 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002127 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002128 } else {
2129 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002130 outInjectionResult = InputEventInjectionResult::PENDING;
2131 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002132 }
2133 }
2134
2135 // we have a valid, non-null focused window
2136 resetNoFocusedWindowTimeoutLocked();
2137
Prabir Pradhan5735a322022-04-11 17:23:34 +00002138 // Verify targeted injection.
2139 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2140 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002141 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2142 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 }
2144
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002145 if (focusedWindowHandle->getInfo()->inputConfig.test(
2146 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002147 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002148 outInjectionResult = InputEventInjectionResult::PENDING;
2149 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002150 }
2151
2152 // If the event is a key event, then we must wait for all previous events to
2153 // complete before delivering it because previous events may have the
2154 // side-effect of transferring focus to a different window and we want to
2155 // ensure that the following keys are sent to the new window.
2156 //
2157 // Suppose the user touches a button in a window then immediately presses "A".
2158 // If the button causes a pop-up window to appear then we want to ensure that
2159 // the "A" key is delivered to the new pop-up window. This is because users
2160 // often anticipate pending UI changes when typing on a keyboard.
2161 // To obtain this behavior, we must serialize key events with respect to all
2162 // prior input events.
2163 if (entry.type == EventEntry::Type::KEY) {
2164 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2165 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002166 outInjectionResult = InputEventInjectionResult::PENDING;
2167 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
2170
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002171 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2172 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173}
2174
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175/**
2176 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2177 * that are currently unresponsive.
2178 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002179std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2180 const std::vector<Monitor>& monitors) const {
2181 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002183 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002184 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002185 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186 if (connection == nullptr) {
2187 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002188 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002189 return false;
2190 }
2191 if (!connection->responsive) {
2192 ALOGW("Unresponsive monitor %s will not get the new gesture",
2193 connection->inputChannel->getName().c_str());
2194 return false;
2195 }
2196 return true;
2197 });
2198 return responsiveMonitors;
2199}
2200
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002201/**
2202 * In general, touch should be always split between windows. Some exceptions:
2203 * 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 -07002204 * from the same device, *and* the window that's receiving the current pointer does not support
2205 * split touch.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002206 * 2. Don't split mouse events
2207 */
2208bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2209 const MotionEntry& entry) const {
2210 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2211 // We should never split mouse events
2212 return false;
2213 }
2214 for (const TouchedWindow& touchedWindow : touchState.windows) {
2215 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2216 // Spy windows should not affect whether or not touch is split.
2217 continue;
2218 }
2219 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2220 continue;
2221 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002222 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2223 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2224 // Wallpaper window should not affect whether or not touch is split
2225 continue;
2226 }
2227
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002228 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002229 return false;
2230 }
2231 }
2232 return true;
2233}
2234
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002235std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002236 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2237 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002238 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002240 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 // For security reasons, we defer updating the touch state until we are sure that
2242 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002243 const int32_t displayId = entry.displayId;
2244 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002245 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
2247 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002248 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 // Copy current touch state into tempTouchState.
2251 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2252 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002253 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002255 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2256 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002257 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002258 }
2259
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002260 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002261 bool switchedDevice = false;
2262 if (oldState != nullptr) {
2263 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2264 const bool anotherDeviceIsActive =
2265 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2266 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002267 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268
2269 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2270 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2271 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002272 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2273 // touchable windows.
2274 const bool wasDown = oldState != nullptr && oldState->isDown();
2275 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2276 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002277 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2278 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2279 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002280 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002281
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002282 // If pointers are already down, let's finish the current gesture and ignore the new events
2283 // from another device. However, if the new event is a down event, let's cancel the current
2284 // touch and let the new one take over.
2285 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002286 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002287 << " is already down in display " << displayId << ": " << entry.getDescription();
2288 // TODO(b/211379801): test multiple simultaneous input streams.
2289 outInjectionResult = InputEventInjectionResult::FAILED;
2290 return {}; // wrong device
2291 }
2292
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002294 // If a new gesture is starting, clear the touch state completely.
2295 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002297 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002298 ALOGI("Dropping move event because a pointer for a different device is already active "
2299 "in display %" PRId32,
2300 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002301 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002302 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002303 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002306 if (isHoverAction) {
2307 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2308 // all of the existing hovering pointers and recompute.
2309 tempTouchState.clearHoveringPointers();
2310 }
2311
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2313 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002314 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002315 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002316 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2317 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002318 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002319 auto [newTouchedWindowHandle, outsideTargets] =
2320 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002321
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002322 if (isDown) {
2323 targets += outsideTargets;
2324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002326 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002327 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002329 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002330 }
2331
Prabir Pradhan5735a322022-04-11 17:23:34 +00002332 // Verify targeted injection.
2333 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2334 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002335 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002336 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002337 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002338 }
2339
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002340 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002341 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002342 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2343 // New window supports splitting, but we should never split mouse events.
2344 isSplit = !isFromMouse;
2345 } else if (isSplit) {
2346 // New window does not support splitting but we have already split events.
2347 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002348 newTouchedWindowHandle = nullptr;
2349 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002350 } else {
2351 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002352 // be delivered to a new window which supports split touch. Pointers from a mouse device
2353 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002354 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002355 }
2356
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002357 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002358 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002359 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002360 // Process the foreground window first so that it is the first to receive the event.
2361 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002362 }
2363
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002364 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002365 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2366 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002367 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002368 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002369 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002370 }
2371
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002372 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002373 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002374 continue;
2375 }
2376
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002377 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2378 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002379 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002380 // The "windowHandle" is the target of this hovering pointer.
2381 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002382 }
2383
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002384 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002385 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002387 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2388 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002389 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002390 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391
2392 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002393 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002394 }
2395 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002396 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002397 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002398 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002400
2401 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002402 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002403 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002404 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002405 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002406
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002407 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2408 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2409
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002410 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2411 // still add a window to the touch state. We should avoid doing that, but some of the
2412 // later checks ("at least one foreground window") rely on this in order to dispatch
2413 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002414 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002415 isDownOrPointerDown
2416 ? std::make_optional(entry.eventTime)
2417 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002418
2419 // If this is the pointer going down and the touched window has a wallpaper
2420 // then also add the touched wallpaper windows so they are locked in for the duration
2421 // of the touch gesture.
2422 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2423 // engine only supports touch events. We would need to add a mechanism similar
2424 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002425 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002426 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2427 windowHandle->getInfo()->inputConfig.test(
2428 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2429 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2430 if (wallpaper != nullptr) {
2431 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2432 InputTarget::Flags::WINDOW_IS_OBSCURED |
2433 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2434 InputTarget::Flags::DISPATCH_AS_IS;
2435 if (isSplit) {
2436 wallpaperFlags |= InputTarget::Flags::SPLIT;
2437 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002438 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2439 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002440 }
2441 }
2442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002444
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002445 // If a window is already pilfering some pointers, give it this new pointer as well and
2446 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2447 // which is a specific behaviour that we want.
2448 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2449 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002450 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2451 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002452 // This window is already pilfering some pointers, and this new pointer is also
2453 // going to it. Therefore, take over this pointer and don't give it to anyone
2454 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002455 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002456 }
2457 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002458
2459 // Restrict all pilfered pointers to the pilfering windows.
2460 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 } else {
2462 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2463
2464 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002465 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002466 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2467 "dropped the pointer down event in display "
2468 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002469 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002470 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
2472
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002473 // If the pointer is not currently hovering, then ignore the event.
2474 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2475 const int32_t pointerId = entry.pointerProperties[0].id;
2476 if (oldState == nullptr ||
2477 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2478 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2479 "display "
2480 << displayId << ": " << entry.getDescription();
2481 outInjectionResult = InputEventInjectionResult::FAILED;
2482 return {};
2483 }
2484 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2485 }
2486
arthurhung6d4bed92021-03-17 11:59:33 +08002487 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002490 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002491 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002492 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002493 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002494 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002495 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002496 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002497 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002498
Prabir Pradhan5735a322022-04-11 17:23:34 +00002499 // Verify targeted injection.
2500 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2501 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002502 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002503 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002504 }
2505
Vishnu Nair062a8672021-09-03 16:07:44 -07002506 // Drop touch events if requested by input feature
2507 if (newTouchedWindowHandle != nullptr &&
2508 shouldDropInput(entry, newTouchedWindowHandle)) {
2509 newTouchedWindowHandle = nullptr;
2510 }
2511
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002512 if (newTouchedWindowHandle != nullptr &&
2513 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002514 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2515 oldTouchedWindowHandle->getName().c_str(),
2516 newTouchedWindowHandle->getName().c_str(), displayId);
2517
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002519 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002520 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002521 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002522
2523 const TouchedWindow& touchedWindow =
2524 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2525 addWindowTargetLocked(oldTouchedWindowHandle,
2526 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002527 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528
2529 // Make a slippery entrance into the new window.
2530 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002531 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 }
2533
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002534 ftl::Flags<InputTarget::Flags> targetFlags =
2535 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002536 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002537 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002540 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002543 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002544 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002545 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 }
2547
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002548 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2549 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002550
2551 // Check if the wallpaper window should deliver the corresponding event.
2552 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002553 tempTouchState, entry.deviceId, pointerId, targets);
2554 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2555 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557 }
Arthur Hung96483742022-11-15 03:30:48 +00002558
2559 // Update the pointerIds for non-splittable when it received pointer down.
2560 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2561 // If no split, we suppose all touched windows should receive pointer down.
2562 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2563 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2564 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2565 // Ignore drag window for it should just track one pointer.
2566 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2567 continue;
2568 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002569 touchedWindow.addTouchingPointer(entry.deviceId,
2570 entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002571 }
2572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 }
2574
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002575 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002576 {
2577 std::vector<TouchedWindow> hoveringWindows =
2578 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2579 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002580 std::optional<InputTarget> target =
2581 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002582 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002583 if (!target) {
2584 continue;
2585 }
2586 // Hardcode to single hovering pointer for now.
2587 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2588 pointerIds.set(entry.pointerProperties[0].id);
2589 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2590 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593
Prabir Pradhan5735a322022-04-11 17:23:34 +00002594 // Ensure that all touched windows are valid for injection.
2595 if (entry.injectionState != nullptr) {
2596 std::string errs;
2597 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002598 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2599 if (err) errs += "\n - " + *err;
2600 }
2601 if (!errs.empty()) {
2602 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002603 "%s:%s",
2604 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002605 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002606 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002607 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002608 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002609
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002610 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2611 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002613 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002614 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002615 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002616 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002617 for (InputTarget& target : targets) {
2618 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2619 sp<WindowInfoHandle> targetWindow =
2620 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2621 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2622 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 }
2625 }
2626 }
2627 }
2628
Harry Cuttsb166c002023-05-09 13:06:05 +00002629 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2630 // only want the system UI to handle these gestures.
2631 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2632 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2633 if (isTouchpadNavGesture) {
2634 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2635 }
2636
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002637 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002638 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002639 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2640 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002641 // Windows with hovering pointers are getting persisted inside TouchState.
2642 // Do not send this event to those windows.
2643 continue;
2644 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002645
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002646 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002647 touchedWindow.getTouchingPointers(entry.deviceId),
2648 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002649 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002650
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002651 // During targeted injection, only allow owned targets to receive events
2652 std::erase_if(targets, [&](const InputTarget& target) {
2653 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2654 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2655 if (err) {
2656 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2657 << ": " << (*err);
2658 return true;
2659 }
2660 return false;
2661 });
2662
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002663 if (targets.empty()) {
2664 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2665 outInjectionResult = InputEventInjectionResult::FAILED;
2666 return {};
2667 }
2668
2669 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2670 // window that is actually receiving the entire gesture.
2671 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2672 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2673 })) {
2674 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2675 << entry.getDescription();
2676 outInjectionResult = InputEventInjectionResult::FAILED;
2677 return {};
2678 }
2679
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002680 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002681 // Drop the outside or hover touch windows since we will not care about them
2682 // in the next iteration.
2683 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002686 if (switchedDevice) {
2687 if (DEBUG_FOCUS) {
2688 ALOGD("Conflicting pointer actions: Switched to a different device.");
2689 }
2690 *outConflictingPointerActions = true;
2691 }
2692
2693 if (isHoverAction) {
2694 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002695 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002696 ALOGD_IF(DEBUG_FOCUS,
2697 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002698 *outConflictingPointerActions = true;
2699 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002700 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2701 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002702 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002703 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2704 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002705 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002706 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002707 // All pointers up or canceled.
2708 tempTouchState.reset();
2709 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2710 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002711 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2712 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002713 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002714 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002715 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2716 // One pointer went up.
2717 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2718 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002720 for (size_t i = 0; i < tempTouchState.windows.size();) {
2721 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002722 touchedWindow.removeTouchingPointer(entry.deviceId, pointerId);
2723 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002724 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2725 continue;
2726 }
2727 i += 1;
2728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 }
2730
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 // Save changes unless the action was scroll in which case the temporary touch
2732 // state was only valid for this one action.
2733 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002734 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002735 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002736 mTouchStatesByDisplay[displayId] = tempTouchState;
2737 } else {
2738 mTouchStatesByDisplay.erase(displayId);
2739 }
2740 }
2741
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002742 if (tempTouchState.windows.empty()) {
2743 mTouchStatesByDisplay.erase(displayId);
2744 }
2745
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002746 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747}
2748
arthurhung6d4bed92021-03-17 11:59:33 +08002749void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002750 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2751 // have an explicit reason to support it.
2752 constexpr bool isStylus = false;
2753
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002754 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002755 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002756 if (dropWindow) {
2757 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002758 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002759 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002760 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002761 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002762 }
2763 mDragState.reset();
2764}
2765
2766void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002767 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002768 return;
2769 }
2770
arthurhung6d4bed92021-03-17 11:59:33 +08002771 if (!mDragState->isStartDrag) {
2772 mDragState->isStartDrag = true;
2773 mDragState->isStylusButtonDownAtStart =
2774 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2775 }
2776
Arthur Hung54745652022-04-20 07:17:41 +00002777 // Find the pointer index by id.
2778 int32_t pointerIndex = 0;
2779 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2780 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2781 if (pointerProperties.id == mDragState->pointerId) {
2782 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002783 }
Arthur Hung54745652022-04-20 07:17:41 +00002784 }
arthurhung6d4bed92021-03-17 11:59:33 +08002785
Arthur Hung54745652022-04-20 07:17:41 +00002786 if (uint32_t(pointerIndex) == entry.pointerCount) {
2787 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002788 }
2789
2790 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2791 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2792 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2793
2794 switch (maskedAction) {
2795 case AMOTION_EVENT_ACTION_MOVE: {
2796 // Handle the special case : stylus button no longer pressed.
2797 bool isStylusButtonDown =
2798 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2799 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2800 finishDragAndDrop(entry.displayId, x, y);
2801 return;
2802 }
2803
2804 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2805 // until we have an explicit reason to support it.
2806 constexpr bool isStylus = false;
2807
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002808 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002809 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002810 // enqueue drag exit if needed.
2811 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2812 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2813 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002814 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002815 y);
2816 }
2817 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2818 }
2819 // enqueue drag location if needed.
2820 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002821 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002822 }
2823 break;
2824 }
2825
2826 case AMOTION_EVENT_ACTION_POINTER_UP:
2827 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2828 break;
2829 }
2830 // The drag pointer is up.
2831 [[fallthrough]];
2832 case AMOTION_EVENT_ACTION_UP:
2833 finishDragAndDrop(entry.displayId, x, y);
2834 break;
2835 case AMOTION_EVENT_ACTION_CANCEL: {
2836 ALOGD("Receiving cancel when drag and drop.");
2837 sendDropWindowCommandLocked(nullptr, 0, 0);
2838 mDragState.reset();
2839 break;
2840 }
arthurhungb89ccb02020-12-30 16:19:01 +08002841 }
2842}
2843
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002844std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2845 const sp<android::gui::WindowInfoHandle>& windowHandle,
2846 ftl::Flags<InputTarget::Flags> targetFlags,
2847 std::optional<nsecs_t> firstDownTimeInTarget) const {
2848 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2849 if (inputChannel == nullptr) {
2850 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2851 return {};
2852 }
2853 InputTarget inputTarget;
2854 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002855 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002856 inputTarget.flags = targetFlags;
2857 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2858 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2859 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2860 if (displayInfoIt != mDisplayInfos.end()) {
2861 inputTarget.displayTransform = displayInfoIt->second.transform;
2862 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002863 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002864 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2865 }
2866 return inputTarget;
2867}
2868
chaviw98318de2021-05-19 16:45:23 -05002869void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002870 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002871 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002872 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002873 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002874 std::vector<InputTarget>::iterator it =
2875 std::find_if(inputTargets.begin(), inputTargets.end(),
2876 [&windowHandle](const InputTarget& inputTarget) {
2877 return inputTarget.inputChannel->getConnectionToken() ==
2878 windowHandle->getToken();
2879 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002880
chaviw98318de2021-05-19 16:45:23 -05002881 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002882
2883 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002884 std::optional<InputTarget> target =
2885 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2886 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002887 return;
2888 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002889 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002890 it = inputTargets.end() - 1;
2891 }
2892
2893 ALOG_ASSERT(it->flags == targetFlags);
2894 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2895
chaviw1ff3d1e2020-07-01 15:53:47 -07002896 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897}
2898
Michael Wright3dd60e22019-03-27 22:06:44 +00002899void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002900 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002901 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2902 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002903
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002904 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2905 InputTarget target;
2906 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002907 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002908 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2909 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002910 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2911 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002912 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002913 target.setDefaultPointerTransform(target.displayTransform);
2914 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 }
2916}
2917
Robert Carrc9bf1d32020-04-13 17:21:08 -07002918/**
2919 * Indicate whether one window handle should be considered as obscuring
2920 * another window handle. We only check a few preconditions. Actually
2921 * checking the bounds is left to the caller.
2922 */
chaviw98318de2021-05-19 16:45:23 -05002923static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2924 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002925 // Compare by token so cloned layers aren't counted
2926 if (haveSameToken(windowHandle, otherHandle)) {
2927 return false;
2928 }
2929 auto info = windowHandle->getInfo();
2930 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002931 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002933 } else if (otherInfo->alpha == 0 &&
2934 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002935 // Those act as if they were invisible, so we don't need to flag them.
2936 // We do want to potentially flag touchable windows even if they have 0
2937 // opacity, since they can consume touches and alter the effects of the
2938 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002939 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002940 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2941 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002942 } else if (info->ownerUid == otherInfo->ownerUid) {
2943 // If ownerUid is the same we don't generate occlusion events as there
2944 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002945 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002946 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002947 return false;
2948 } else if (otherInfo->displayId != info->displayId) {
2949 return false;
2950 }
2951 return true;
2952}
2953
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002954/**
2955 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2956 * untrusted, one should check:
2957 *
2958 * 1. If result.hasBlockingOcclusion is true.
2959 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2960 * BLOCK_UNTRUSTED.
2961 *
2962 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2963 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2964 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2965 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2966 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2967 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2968 *
2969 * If neither of those is true, then it means the touch can be allowed.
2970 */
2971InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002972 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2973 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002974 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002975 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002976 TouchOcclusionInfo info;
2977 info.hasBlockingOcclusion = false;
2978 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002979 info.obscuringUid = gui::Uid::INVALID;
2980 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002981 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002982 if (windowHandle == otherHandle) {
2983 break; // All future windows are below us. Exit early.
2984 }
chaviw98318de2021-05-19 16:45:23 -05002985 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002986 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2987 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002988 if (DEBUG_TOUCH_OCCLUSION) {
2989 info.debugInfo.push_back(
2990 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2991 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002992 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2993 // we perform the checks below to see if the touch can be propagated or not based on the
2994 // window's touch occlusion mode
2995 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2996 info.hasBlockingOcclusion = true;
2997 info.obscuringUid = otherInfo->ownerUid;
2998 info.obscuringPackage = otherInfo->packageName;
2999 break;
3000 }
3001 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003002 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003003 float opacity =
3004 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3005 // Given windows A and B:
3006 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3007 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3008 opacityByUid[uid] = opacity;
3009 if (opacity > info.obscuringOpacity) {
3010 info.obscuringOpacity = opacity;
3011 info.obscuringUid = uid;
3012 info.obscuringPackage = otherInfo->packageName;
3013 }
3014 }
3015 }
3016 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003017 if (DEBUG_TOUCH_OCCLUSION) {
3018 info.debugInfo.push_back(
3019 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
3020 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003021 return info;
3022}
3023
chaviw98318de2021-05-19 16:45:23 -05003024std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003025 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003026 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003027 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3028 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3029 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003030 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003031 info->ownerUid.toString().c_str(), info->id,
3032 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
3033 info->frameTop, info->frameRight, info->frameBottom,
3034 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3035 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3036 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003037 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003038}
3039
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003040bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3041 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003042 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3043 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003044 return false;
3045 }
3046 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003047 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003048 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003049 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003050 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3051 return false;
3052 }
3053 return true;
3054}
3055
chaviw98318de2021-05-19 16:45:23 -05003056bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003057 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003059 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3060 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003061 if (windowHandle == otherHandle) {
3062 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 }
chaviw98318de2021-05-19 16:45:23 -05003064 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003065 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003066 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 return true;
3068 }
3069 }
3070 return false;
3071}
3072
chaviw98318de2021-05-19 16:45:23 -05003073bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003074 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003075 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3076 const WindowInfo* windowInfo = windowHandle->getInfo();
3077 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003078 if (windowHandle == otherHandle) {
3079 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003080 }
chaviw98318de2021-05-19 16:45:23 -05003081 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003082 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003083 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003084 return true;
3085 }
3086 }
3087 return false;
3088}
3089
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003090std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003091 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003092 if (applicationHandle != nullptr) {
3093 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003094 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 } else {
3096 return applicationHandle->getName();
3097 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003098 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003099 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003101 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102 }
3103}
3104
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003105void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003106 if (!isUserActivityEvent(eventEntry)) {
3107 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003108 return;
3109 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003110 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003111 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003112 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003113 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003114 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003115 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003116 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118 }
3119
3120 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003121 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003122 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003123 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3124 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 return;
3126 }
Josep del Riob3981622023-04-18 15:49:45 +00003127 if (windowDisablingUserActivityInfo != nullptr) {
3128 if (DEBUG_DISPATCH_CYCLE) {
3129 ALOGD("Not poking user activity: disabled by window '%s'.",
3130 windowDisablingUserActivityInfo->name.c_str());
3131 }
3132 return;
3133 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 eventType = USER_ACTIVITY_EVENT_TOUCH;
3136 }
3137 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003139 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003140 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3141 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 return;
3143 }
Josep del Riob3981622023-04-18 15:49:45 +00003144 // If the key code is unknown, we don't consider it user activity
3145 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3146 return;
3147 }
3148 // Don't inhibit events that were intercepted or are not passed to
3149 // the apps, like system shortcuts
3150 if (windowDisablingUserActivityInfo != nullptr &&
3151 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3152 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3153 if (DEBUG_DISPATCH_CYCLE) {
3154 ALOGD("Not poking user activity: disabled by window '%s'.",
3155 windowDisablingUserActivityInfo->name.c_str());
3156 }
3157 return;
3158 }
3159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 eventType = USER_ACTIVITY_EVENT_BUTTON;
3161 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003163 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003164 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003165 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003166 break;
3167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
3169
Prabir Pradhancef936d2021-07-21 16:17:52 +00003170 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3171 REQUIRES(mLock) {
3172 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003173 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003174 };
3175 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176}
3177
3178void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003179 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003181 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003182 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003184 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003185 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003186 ATRACE_NAME(message.c_str());
3187 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003188 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003189 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003190 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003192 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003193 inputTarget.getPointerInfoString().c_str());
3194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195
3196 // Skip this event if the connection status is not normal.
3197 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003198 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003199 if (DEBUG_DISPATCH_CYCLE) {
3200 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003201 connection->getInputChannelName().c_str(),
3202 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 return;
3205 }
3206
3207 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003208 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003209 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003210 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003211 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003213 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003214 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003215 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3216 logDispatchStateLocked();
3217 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3218 "target on connection "
3219 << connection->getInputChannelName() << " for "
3220 << originalMotionEntry.getDescription();
3221 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003222 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003223 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3224 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 if (!splitMotionEntry) {
3226 return; // split event was dropped
3227 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003228 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3229 std::string reason = std::string("reason=pointer cancel on split window");
3230 android_log_event_list(LOGTAG_INPUT_CANCEL)
3231 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3232 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003233 if (DEBUG_FOCUS) {
3234 ALOGD("channel '%s' ~ Split motion event.",
3235 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003236 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003237 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003238 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3239 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 return;
3241 }
3242 }
3243
3244 // Not splitting. Enqueue dispatch entries for the event as is.
3245 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3246}
3247
3248void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003249 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003251 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003252 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003254 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003255 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003256 ATRACE_NAME(message.c_str());
3257 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003258 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3259 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003260
hongzuo liu95785e22022-09-06 02:51:35 +00003261 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262
3263 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003264 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003265 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003266 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003268 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003269 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003270 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003271 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003272 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003273 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003274 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276
3277 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003278 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 startDispatchCycleLocked(currentTime, connection);
3280 }
3281}
3282
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003283void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003284 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003285 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003286 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003287 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3289 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003290 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003291 ATRACE_NAME(message.c_str());
3292 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3294 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 return;
3296 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297
3298 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3299 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
3301 // This is a new event.
3302 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003303 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003304 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003306 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3307 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003310 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003311 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003313 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003314 dispatchEntry->resolvedAction = keyEntry.action;
3315 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3318 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003319 LOG(WARNING) << "channel " << connection->getInputChannelName()
3320 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 return; // skip the inconsistent event
3322 }
3323 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003326 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003327 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003328 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3329 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3330 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3331 static_cast<int32_t>(IdGenerator::Source::OTHER);
3332 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003333 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003335 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003337 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003339 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003340 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003341 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3343 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003344 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003345 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 }
3347 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003348 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3349 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003350 if (DEBUG_DISPATCH_CYCLE) {
3351 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3352 "enter event",
3353 connection->getInputChannelName().c_str());
3354 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003355 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3356 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003360 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003361 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3362 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3363 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003364 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3366 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003367 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003371 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3372 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003373 LOG(WARNING) << "channel " << connection->getInputChannelName()
3374 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003375 return; // skip the inconsistent event
3376 }
3377
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003378 dispatchEntry->resolvedEventId =
3379 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3380 ? mIdGenerator.nextId()
3381 : motionEntry.id;
3382 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3383 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3384 ") to MotionEvent(id=0x%" PRIx32 ").",
3385 motionEntry.id, dispatchEntry->resolvedEventId);
3386 ATRACE_NAME(message.c_str());
3387 }
3388
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003389 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3390 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3391 // Skip reporting pointer down outside focus to the policy.
3392 break;
3393 }
3394
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003395 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003396 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397
3398 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003400 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003401 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003402 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3403 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003404 break;
3405 }
Chris Yef59a2f42020-10-16 12:55:26 -07003406 case EventEntry::Type::SENSOR: {
3407 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3408 break;
3409 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003410 case EventEntry::Type::CONFIGURATION_CHANGED:
3411 case EventEntry::Type::DEVICE_RESET: {
3412 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003413 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003414 break;
3415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417
3418 // Remember that we are waiting for this dispatch to complete.
3419 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003420 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422
3423 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003424 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003425 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003426}
3427
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003428/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003429 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003430 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003431 * The first role is to log input interaction with windows, which helps determine what the user was
3432 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3433 * that user started interacting with launcher window, as well as any other window that received
3434 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3435 * when the set of tokens that received the event changes. It is not logged again as long as the
3436 * user is interacting with the same windows.
3437 *
3438 * The second role is to track input device activity for metrics collection. For each input event,
3439 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3440 * input_interaction logs, the device interaction is reported even when the set of interaction
3441 * tokens do not change.
3442 *
3443 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3444 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003445 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003446void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3447 const std::vector<InputTarget>& targets) {
3448 int32_t deviceId;
3449 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003450 // Skip ACTION_UP events, and all events other than keys and motions
3451 if (entry.type == EventEntry::Type::KEY) {
3452 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3453 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3454 return;
3455 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003456 deviceId = keyEntry.deviceId;
3457 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003458 } else if (entry.type == EventEntry::Type::MOTION) {
3459 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3460 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003461 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3462 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003463 return;
3464 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003465 deviceId = motionEntry.deviceId;
3466 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003467 } else {
3468 return; // Not a key or a motion
3469 }
3470
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003471 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003472 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003473 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003475 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003476 continue; // Skip windows that receive ACTION_OUTSIDE
3477 }
3478
3479 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003480 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003481 if (connection == nullptr) {
3482 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003483 }
3484 newConnectionTokens.insert(std::move(token));
3485 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003486 if (target.windowHandle) {
3487 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3488 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003489 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003490
3491 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3492 REQUIRES(mLock) {
3493 scoped_unlock unlock(mLock);
3494 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3495 };
3496 postCommandLocked(std::move(command));
3497
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003498 if (newConnectionTokens == mInteractionConnectionTokens) {
3499 return; // no change
3500 }
3501 mInteractionConnectionTokens = newConnectionTokens;
3502
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003503 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003504 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003505 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003506 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003507 std::string message = "Interaction with: " + targetList;
3508 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003509 message += "<none>";
3510 }
3511 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3512}
3513
chaviwfd6d3512019-03-25 13:23:49 -07003514void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003515 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003516 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003517 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3518 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003519 return;
3520 }
3521
Vishnu Nairc519ff72021-01-21 08:23:08 -08003522 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003523 if (focusedToken == token) {
3524 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003525 return;
3526 }
3527
Prabir Pradhancef936d2021-07-21 16:17:52 +00003528 auto command = [this, token]() REQUIRES(mLock) {
3529 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003530 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003531 };
3532 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533}
3534
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003535status_t InputDispatcher::publishMotionEvent(Connection& connection,
3536 DispatchEntry& dispatchEntry) const {
3537 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3538 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3539
3540 PointerCoords scaledCoords[MAX_POINTERS];
3541 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3542
3543 // Set the X and Y offset and X and Y scale depending on the input source.
3544 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003545 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003546 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3547 if (globalScaleFactor != 1.0f) {
3548 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3549 scaledCoords[i] = motionEntry.pointerCoords[i];
3550 // Don't apply window scale here since we don't want scale to affect raw
3551 // coordinates. The scale will be sent back to the client and applied
3552 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003553 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003554 }
3555 usingCoords = scaledCoords;
3556 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003557 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003558 // We don't want the dispatch target to know the coordinates
3559 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3560 scaledCoords[i].clear();
3561 }
3562 usingCoords = scaledCoords;
3563 }
3564
3565 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3566
3567 // Publish the motion event.
3568 return connection.inputPublisher
3569 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3570 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3571 std::move(hmac), dispatchEntry.resolvedAction,
3572 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3573 motionEntry.edgeFlags, motionEntry.metaState,
3574 motionEntry.buttonState, motionEntry.classification,
3575 dispatchEntry.transform, motionEntry.xPrecision,
3576 motionEntry.yPrecision, motionEntry.xCursorPosition,
3577 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3578 motionEntry.downTime, motionEntry.eventTime,
3579 motionEntry.pointerCount, motionEntry.pointerProperties,
3580 usingCoords);
3581}
3582
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003584 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003585 if (ATRACE_ENABLED()) {
3586 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003587 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003588 ATRACE_NAME(message.c_str());
3589 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003590 if (DEBUG_DISPATCH_CYCLE) {
3591 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003594 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003595 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003597 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003598 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599
3600 // Publish the event.
3601 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3603 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003604 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003605 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3606 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003607 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3608 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3609 << connection->getInputChannelName();
3610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003613 status = connection->inputPublisher
3614 .publishKeyEvent(dispatchEntry->seq,
3615 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3616 keyEntry.source, keyEntry.displayId,
3617 std::move(hmac), dispatchEntry->resolvedAction,
3618 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3619 keyEntry.scanCode, keyEntry.metaState,
3620 keyEntry.repeatCount, keyEntry.downTime,
3621 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003625 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003626 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3627 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3628 << connection->getInputChannelName();
3629 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003630 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003631 break;
3632 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003633
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003634 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003635 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003636 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003637 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003638 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003639 break;
3640 }
3641
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003642 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3643 const TouchModeEntry& touchModeEntry =
3644 static_cast<const TouchModeEntry&>(eventEntry);
3645 status = connection->inputPublisher
3646 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3647 touchModeEntry.inTouchMode);
3648
3649 break;
3650 }
3651
Prabir Pradhan99987712020-11-10 18:43:05 -08003652 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3653 const auto& captureEntry =
3654 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3655 status = connection->inputPublisher
3656 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003657 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003658 break;
3659 }
3660
arthurhungb89ccb02020-12-30 16:19:01 +08003661 case EventEntry::Type::DRAG: {
3662 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3663 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3664 dragEntry.id, dragEntry.x,
3665 dragEntry.y,
3666 dragEntry.isExiting);
3667 break;
3668 }
3669
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003670 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003671 case EventEntry::Type::DEVICE_RESET:
3672 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003673 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003674 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003675 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 }
3678
3679 // Check the result.
3680 if (status) {
3681 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003682 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003684 "This is unexpected because the wait queue is empty, so the pipe "
3685 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003686 "event to it, status=%s(%d)",
3687 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3688 status);
Harry Cutts33476232023-01-30 19:57:29 +00003689 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 } else {
3691 // Pipe is full and we are waiting for the app to finish process some events
3692 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003693 if (DEBUG_DISPATCH_CYCLE) {
3694 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3695 "waiting for the application to catch up",
3696 connection->getInputChannelName().c_str());
3697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699 } else {
3700 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003701 "status=%s(%d)",
3702 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3703 status);
Harry Cutts33476232023-01-30 19:57:29 +00003704 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
3706 return;
3707 }
3708
3709 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003710 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3711 connection->outboundQueue.end(),
3712 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003713 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003714 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003715 if (connection->responsive) {
3716 mAnrTracker.insert(dispatchEntry->timeoutTime,
3717 connection->inputChannel->getConnectionToken());
3718 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003719 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 }
3721}
3722
chaviw09c8d2d2020-08-24 15:48:26 -07003723std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3724 size_t size;
3725 switch (event.type) {
3726 case VerifiedInputEvent::Type::KEY: {
3727 size = sizeof(VerifiedKeyEvent);
3728 break;
3729 }
3730 case VerifiedInputEvent::Type::MOTION: {
3731 size = sizeof(VerifiedMotionEvent);
3732 break;
3733 }
3734 }
3735 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3736 return mHmacKeyManager.sign(start, size);
3737}
3738
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003739const std::array<uint8_t, 32> InputDispatcher::getSignature(
3740 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003741 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003742 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003743 // Only sign events up and down events as the purely move events
3744 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003745 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003746 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003747
3748 VerifiedMotionEvent verifiedEvent =
3749 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3750 verifiedEvent.actionMasked = actionMasked;
3751 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3752 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003753}
3754
3755const std::array<uint8_t, 32> InputDispatcher::getSignature(
3756 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3757 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3758 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3759 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003760 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003761}
3762
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003764 const std::shared_ptr<Connection>& connection,
3765 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003766 if (DEBUG_DISPATCH_CYCLE) {
3767 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3768 connection->getInputChannelName().c_str(), seq, toString(handled));
3769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003771 if (connection->status == Connection::Status::BROKEN ||
3772 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 return;
3774 }
3775
3776 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003777 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3778 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3779 };
3780 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781}
3782
3783void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003784 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003786 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003787 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3788 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790
3791 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003792 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003793 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003794 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003795 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
3797 // The connection appears to be unrecoverably broken.
3798 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003799 if (connection->status == Connection::Status::NORMAL) {
3800 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801
3802 if (notify) {
3803 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003804 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3805 connection->getInputChannelName().c_str());
3806
3807 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003808 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003809 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003810 };
3811 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813 }
3814}
3815
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003816void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3817 while (!queue.empty()) {
3818 DispatchEntry* dispatchEntry = queue.front();
3819 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003820 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822}
3823
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003824void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003826 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
3828 delete dispatchEntry;
3829}
3830
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003831int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3832 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003833 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003834 if (connection == nullptr) {
3835 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3836 connectionToken.get(), events);
3837 return 0; // remove the callback
3838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003840 bool notify;
3841 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3842 if (!(events & ALOOPER_EVENT_INPUT)) {
3843 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3844 "events=0x%x",
3845 connection->getInputChannelName().c_str(), events);
3846 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 }
3848
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003849 nsecs_t currentTime = now();
3850 bool gotOne = false;
3851 status_t status = OK;
3852 for (;;) {
3853 Result<InputPublisher::ConsumerResponse> result =
3854 connection->inputPublisher.receiveConsumerResponse();
3855 if (!result.ok()) {
3856 status = result.error().code();
3857 break;
3858 }
3859
3860 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3861 const InputPublisher::Finished& finish =
3862 std::get<InputPublisher::Finished>(*result);
3863 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3864 finish.consumeTime);
3865 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003866 if (shouldReportMetricsForConnection(*connection)) {
3867 const InputPublisher::Timeline& timeline =
3868 std::get<InputPublisher::Timeline>(*result);
3869 mLatencyTracker
3870 .trackGraphicsLatency(timeline.inputEventId,
3871 connection->inputChannel->getConnectionToken(),
3872 std::move(timeline.graphicsTimeline));
3873 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003874 }
3875 gotOne = true;
3876 }
3877 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003878 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003879 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 return 1;
3881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003884 notify = status != DEAD_OBJECT || !connection->monitor;
3885 if (notify) {
3886 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3887 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3888 status);
3889 }
3890 } else {
3891 // Monitor channels are never explicitly unregistered.
3892 // We do it automatically when the remote endpoint is closed so don't warn about them.
3893 const bool stillHaveWindowHandle =
3894 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3895 notify = !connection->monitor && stillHaveWindowHandle;
3896 if (notify) {
3897 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3898 connection->getInputChannelName().c_str(), events);
3899 }
3900 }
3901
3902 // Remove the channel.
3903 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3904 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905}
3906
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003907void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003909 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003910 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 }
3912}
3913
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003914void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003915 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003916 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003917 for (const Monitor& monitor : monitors) {
3918 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003919 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003920 }
3921}
3922
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003924 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003925 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003926 if (connection == nullptr) {
3927 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003929
3930 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931}
3932
3933void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003934 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Lia4659fc2023-07-14 14:36:22 +08003935 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3936 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3937 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3938 LOG(INFO) << __func__
3939 << ": Canceling drag and drop because the pointers for the drag window are being "
3940 "canceled.";
3941 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3942 mDragState.reset();
3943 }
3944
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003945 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 return;
3947 }
3948
3949 nsecs_t currentTime = now();
3950
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003951 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003952 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003954 if (cancelationEvents.empty()) {
3955 return;
3956 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003957 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3958 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003959 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003960 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003961 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003962 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003963
Arthur Hungb3307ee2021-10-14 10:57:37 +00003964 std::string reason = std::string("reason=").append(options.reason);
3965 android_log_event_list(LOGTAG_INPUT_CANCEL)
3966 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3967
Svet Ganov5d3bc372020-01-26 23:11:07 -08003968 InputTarget target;
Hu Guoca59f112023-09-17 20:51:08 +08003969 sp<WindowInfoHandle> windowHandle;
3970 if (options.displayId) {
3971 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3972 options.displayId.value());
3973 } else {
3974 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3975 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003976 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003977 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003978 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003979 target.globalScaleFactor = windowInfo->globalScaleFactor;
3980 }
3981 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003982 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003983
hongzuo liu95785e22022-09-06 02:51:35 +00003984 const bool wasEmpty = connection->outboundQueue.empty();
3985
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003987 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003988 switch (cancelationEventEntry->type) {
3989 case EventEntry::Type::KEY: {
3990 logOutboundKeyDetails("cancel - ",
3991 static_cast<const KeyEntry&>(*cancelationEventEntry));
3992 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003994 case EventEntry::Type::MOTION: {
3995 logOutboundMotionDetails("cancel - ",
3996 static_cast<const MotionEntry&>(*cancelationEventEntry));
3997 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003999 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004000 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004001 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4002 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004003 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004004 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004005 break;
4006 }
4007 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004008 case EventEntry::Type::DEVICE_RESET:
4009 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004010 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004011 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004012 break;
4013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 }
4015
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004016 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004017 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004019
hongzuo liu95785e22022-09-06 02:51:35 +00004020 // If the outbound queue was previously empty, start the dispatch cycle going.
4021 if (wasEmpty && !connection->outboundQueue.empty()) {
4022 startDispatchCycleLocked(currentTime, connection);
4023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024}
4025
Svet Ganov5d3bc372020-01-26 23:11:07 -08004026void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004027 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004028 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004029 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004030 return;
4031 }
4032
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004033 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004034 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004035
4036 if (downEvents.empty()) {
4037 return;
4038 }
4039
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004040 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004041 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4042 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004043 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004044
4045 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004046 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004047 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4048 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004049 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004050 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004051 target.globalScaleFactor = windowInfo->globalScaleFactor;
4052 }
4053 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004054 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004055
hongzuo liu95785e22022-09-06 02:51:35 +00004056 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004057 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004058 switch (downEventEntry->type) {
4059 case EventEntry::Type::MOTION: {
4060 logOutboundMotionDetails("down - ",
4061 static_cast<const MotionEntry&>(*downEventEntry));
4062 break;
4063 }
4064
4065 case EventEntry::Type::KEY:
4066 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004067 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004068 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004069 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004070 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004071 case EventEntry::Type::SENSOR:
4072 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004073 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004074 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004075 break;
4076 }
4077 }
4078
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004080 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004081 }
4082
hongzuo liu95785e22022-09-06 02:51:35 +00004083 // If the outbound queue was previously empty, start the dispatch cycle going.
4084 if (wasEmpty && !connection->outboundQueue.empty()) {
4085 startDispatchCycleLocked(downTime, connection);
4086 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004087}
4088
Arthur Hungc539dbb2022-12-08 07:45:36 +00004089void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4090 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4091 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004092 std::shared_ptr<Connection> wallpaperConnection =
4093 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004094 if (wallpaperConnection != nullptr) {
4095 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4096 }
4097 }
4098}
4099
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004100std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004101 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4102 nsecs_t splitDownTime) {
4103 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104
4105 uint32_t splitPointerIndexMap[MAX_POINTERS];
4106 PointerProperties splitPointerProperties[MAX_POINTERS];
4107 PointerCoords splitPointerCoords[MAX_POINTERS];
4108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004109 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 uint32_t splitPointerCount = 0;
4111
4112 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004115 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004117 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
4119 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
4120 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004121 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 splitPointerCount += 1;
4123 }
4124 }
4125
4126 if (splitPointerCount != pointerIds.count()) {
4127 // This is bad. We are missing some of the pointers that we expected to deliver.
4128 // Most likely this indicates that we received an ACTION_MOVE events that has
4129 // different pointer ids than we expected based on the previous ACTION_DOWN
4130 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4131 // in this way.
4132 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004133 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004134 "a broken sequence of pointer ids from the input device: %s",
4135 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004136 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
4138
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004139 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4142 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
4144 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004145 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004147 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 if (pointerIds.count() == 1) {
4149 // The first/last pointer went down/up.
4150 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004152 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4153 ? AMOTION_EVENT_ACTION_CANCEL
4154 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 } else {
4156 // A secondary pointer went down/up.
4157 uint32_t splitPointerIndex = 0;
4158 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4159 splitPointerIndex += 1;
4160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 action = maskedAction |
4162 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
4164 } else {
4165 // An unrelated pointer changed.
4166 action = AMOTION_EVENT_ACTION_MOVE;
4167 }
4168 }
4169
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004170 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4171 logDispatchStateLocked();
4172 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4173 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4174 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004175 }
4176
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004177 int32_t newId = mIdGenerator.nextId();
4178 if (ATRACE_ENABLED()) {
4179 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4180 ") to MotionEvent(id=0x%" PRIx32 ").",
4181 originalMotionEntry.id, newId);
4182 ATRACE_NAME(message.c_str());
4183 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004184 std::unique_ptr<MotionEntry> splitMotionEntry =
4185 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4186 originalMotionEntry.deviceId, originalMotionEntry.source,
4187 originalMotionEntry.displayId,
4188 originalMotionEntry.policyFlags, action,
4189 originalMotionEntry.actionButton,
4190 originalMotionEntry.flags, originalMotionEntry.metaState,
4191 originalMotionEntry.buttonState,
4192 originalMotionEntry.classification,
4193 originalMotionEntry.edgeFlags,
4194 originalMotionEntry.xPrecision,
4195 originalMotionEntry.yPrecision,
4196 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004197 originalMotionEntry.yCursorPosition, splitDownTime,
4198 splitPointerCount, splitPointerProperties,
4199 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004201 if (originalMotionEntry.injectionState) {
4202 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 splitMotionEntry->injectionState->refCount += 1;
4204 }
4205
4206 return splitMotionEntry;
4207}
4208
Prabir Pradhan678438e2023-04-13 19:32:51 +00004209void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004210 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004211 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213
Antonio Kantekf16f2832021-09-28 04:39:20 +00004214 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004216 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004218 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004219 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004220 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 } // release lock
4222
4223 if (needWake) {
4224 mLooper->wake();
4225 }
4226}
4227
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004228/**
4229 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004230 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4231 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4232 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4233 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4234 * potentially handle the back key presses.
4235 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4236 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004237 */
4238void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004240 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4241 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004242 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004243 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004244 }
4245 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004246 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004247 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004248 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004249 keyCode = newKeyCode;
4250 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4251 }
4252 } else if (action == AKEY_EVENT_ACTION_UP) {
4253 // In order to maintain a consistent stream of up and down events, check to see if the key
4254 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4255 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004256 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004257 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004258 auto replacementIt = mReplacedKeys.find(replacement);
4259 if (replacementIt != mReplacedKeys.end()) {
4260 keyCode = replacementIt->second;
4261 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004262 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4263 }
4264 }
4265}
4266
Prabir Pradhan678438e2023-04-13 19:32:51 +00004267void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004268 ALOGD_IF(debugInboundEventDetails(),
4269 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4270 ", deviceId=%d, source=%s, displayId=%" PRId32
4271 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4272 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004273 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4274 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4275 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004276 Result<void> keyCheck = validateKeyEvent(args.action);
4277 if (!keyCheck.ok()) {
4278 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 return;
4280 }
4281
Prabir Pradhan678438e2023-04-13 19:32:51 +00004282 uint32_t policyFlags = args.policyFlags;
4283 int32_t flags = args.flags;
4284 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004285 // InputDispatcher tracks and generates key repeats on behalf of
4286 // whatever notifies it, so repeatCount should always be set to 0
4287 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4289 policyFlags |= POLICY_FLAG_VIRTUAL;
4290 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 if (policyFlags & POLICY_FLAG_FUNCTION) {
4293 metaState |= AMETA_FUNCTION_ON;
4294 }
4295
4296 policyFlags |= POLICY_FLAG_TRUSTED;
4297
Prabir Pradhan678438e2023-04-13 19:32:51 +00004298 int32_t keyCode = args.keyCode;
4299 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004300
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004302 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4303 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4304 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305
Michael Wright2b3c3302018-03-02 17:19:13 +00004306 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004307 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004308 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4309 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
Antonio Kantekf16f2832021-09-28 04:39:20 +00004313 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 { // acquire lock
4315 mLock.lock();
4316
4317 if (shouldSendKeyToInputFilterLocked(args)) {
4318 mLock.unlock();
4319
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004320 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004321 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 return; // event was consumed by the filter
4323 }
4324
4325 mLock.lock();
4326 }
4327
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004328 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004329 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4330 args.displayId, policyFlags, args.action, flags, keyCode,
4331 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004333 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 mLock.unlock();
4335 } // release lock
4336
4337 if (needWake) {
4338 mLooper->wake();
4339 }
4340}
4341
Prabir Pradhan678438e2023-04-13 19:32:51 +00004342bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 return mInputFilterEnabled;
4344}
4345
Prabir Pradhan678438e2023-04-13 19:32:51 +00004346void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004347 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004348 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004349 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004350 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004351 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4352 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004353 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4354 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4355 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4356 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4357 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004358 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004359 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4360 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004361 i, args.pointerProperties[i].id,
4362 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4363 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4364 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4365 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4366 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4367 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4368 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4369 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4370 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4371 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004374
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004375 Result<void> motionCheck =
4376 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4377 args.pointerProperties.data());
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004378 if (!motionCheck.ok()) {
4379 LOG(ERROR) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004380 return;
4381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004383 if (DEBUG_VERIFY_EVENTS) {
4384 auto [it, _] =
4385 mVerifiersByDisplay.try_emplace(args.displayId,
4386 StringPrintf("display %" PRId32, args.displayId));
4387 Result<void> result =
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004388 it->second.processMovement(args.deviceId, args.action, args.getPointerCount(),
4389 args.pointerProperties.data(), args.pointerCoords.data(),
4390 args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004391 if (!result.ok()) {
4392 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4393 }
4394 }
4395
Prabir Pradhan678438e2023-04-13 19:32:51 +00004396 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004398
4399 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004400 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004401 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4402 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
Antonio Kantekf16f2832021-09-28 04:39:20 +00004406 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 { // acquire lock
4408 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004409 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4410 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4411 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004412 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004413 if (touchStateIt != mTouchStatesByDisplay.end()) {
4414 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004415 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004416 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4417 }
4418 }
4419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420
4421 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004422 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004423 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004424 displayTransform = it->second.transform;
4425 }
4426
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 mLock.unlock();
4428
4429 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004430 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4431 args.action, args.actionButton, args.flags, args.edgeFlags,
4432 args.metaState, args.buttonState, args.classification,
4433 displayTransform, args.xPrecision, args.yPrecision,
4434 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004435 args.downTime, args.eventTime, args.getPointerCount(),
4436 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
4438 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004439 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 return; // event was consumed by the filter
4441 }
4442
4443 mLock.lock();
4444 }
4445
4446 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004447 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004448 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4449 args.displayId, policyFlags, args.action,
4450 args.actionButton, args.flags, args.metaState,
4451 args.buttonState, args.classification, args.edgeFlags,
4452 args.xPrecision, args.yPrecision,
4453 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004454 args.downTime, args.getPointerCount(),
4455 args.pointerProperties.data(),
4456 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457
Prabir Pradhan678438e2023-04-13 19:32:51 +00004458 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4459 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004460 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004461 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4462 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004463 }
4464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004465 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 mLock.unlock();
4467 } // release lock
4468
4469 if (needWake) {
4470 mLooper->wake();
4471 }
4472}
4473
Prabir Pradhan678438e2023-04-13 19:32:51 +00004474void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004475 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4477 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004478 args.id, args.eventTime, args.deviceId, args.source,
4479 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004480 }
Chris Yef59a2f42020-10-16 12:55:26 -07004481
Antonio Kantekf16f2832021-09-28 04:39:20 +00004482 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004483 { // acquire lock
4484 mLock.lock();
4485
4486 // Just enqueue a new sensor event.
4487 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004488 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4489 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4490 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004491
4492 needWake = enqueueInboundEventLocked(std::move(newEntry));
4493 mLock.unlock();
4494 } // release lock
4495
4496 if (needWake) {
4497 mLooper->wake();
4498 }
4499}
4500
Prabir Pradhan678438e2023-04-13 19:32:51 +00004501void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004502 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004503 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4504 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004505 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004506 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004507}
4508
Prabir Pradhan678438e2023-04-13 19:32:51 +00004509bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004510 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511}
4512
Prabir Pradhan678438e2023-04-13 19:32:51 +00004513void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004514 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004515 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4516 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004517 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519
Prabir Pradhan678438e2023-04-13 19:32:51 +00004520 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004522 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523}
4524
Prabir Pradhan678438e2023-04-13 19:32:51 +00004525void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004526 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004527 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4528 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530
Antonio Kantekf16f2832021-09-28 04:39:20 +00004531 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004533 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004535 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004536 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004537 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 } // release lock
4539
4540 if (needWake) {
4541 mLooper->wake();
4542 }
4543}
4544
Prabir Pradhan678438e2023-04-13 19:32:51 +00004545void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004546 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004547 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4548 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004549 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004550
Antonio Kantekf16f2832021-09-28 04:39:20 +00004551 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004552 { // acquire lock
4553 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004554 auto entry =
4555 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004556 needWake = enqueueInboundEventLocked(std::move(entry));
4557 } // release lock
4558
4559 if (needWake) {
4560 mLooper->wake();
4561 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004562}
4563
Prabir Pradhan5735a322022-04-11 17:23:34 +00004564InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004565 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004566 InputEventInjectionSync syncMode,
4567 std::chrono::milliseconds timeout,
4568 uint32_t policyFlags) {
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004569 Result<void> eventValidation = validateInputEvent(*event);
4570 if (!eventValidation.ok()) {
4571 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4572 return InputEventInjectionResult::FAILED;
4573 }
4574
Prabir Pradhan65613802023-02-22 23:36:58 +00004575 if (debugInboundEventDetails()) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004576 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004577 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4578 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4579 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004580 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004581 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582
Prabir Pradhan5735a322022-04-11 17:23:34 +00004583 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004585 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004586 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4587 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4588 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4589 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4590 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004591 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004592 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004593 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004594 }
4595
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004596 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004598 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004599 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004600 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004601 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004602 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4603 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4604 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004605 int32_t keyCode = incomingKey.getKeyCode();
4606 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004607 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004608 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004609 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004610 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004611 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4612 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4613 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4616 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004617 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618
4619 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4620 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004621 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4623 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4624 std::to_string(t.duration().count()).c_str());
4625 }
4626 }
4627
4628 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004629 std::unique_ptr<KeyEntry> injectedEntry =
4630 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004631 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004632 incomingKey.getDisplayId(), policyFlags, action,
4633 flags, keyCode, incomingKey.getScanCode(), metaState,
4634 incomingKey.getRepeatCount(),
4635 incomingKey.getDownTime());
4636 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004637 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 }
4639
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004640 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004641 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004642 const bool isPointerEvent =
4643 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4644 // If a pointer event has no displayId specified, inject it to the default display.
4645 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4646 ? ADISPLAY_ID_DEFAULT
4647 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004648 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004649
4650 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004653 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004654 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4655 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4656 std::to_string(t.duration().count()).c_str());
4657 }
4658 }
4659
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004660 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4661 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4662 }
4663
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004664 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004665 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4666 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004667 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004668 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4669 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004670 displayId, policyFlags, motionEvent.getAction(),
4671 motionEvent.getActionButton(), flags,
4672 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004673 motionEvent.getButtonState(),
4674 motionEvent.getClassification(),
4675 motionEvent.getEdgeFlags(),
4676 motionEvent.getXPrecision(),
4677 motionEvent.getYPrecision(),
4678 motionEvent.getRawXCursorPosition(),
4679 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004680 motionEvent.getDownTime(),
4681 motionEvent.getPointerCount(),
4682 motionEvent.getPointerProperties(),
4683 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004684 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004685 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004686 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004687 sampleEventTimes += 1;
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004688 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004689 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004690 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4691 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004692 displayId, policyFlags,
4693 motionEvent.getAction(),
4694 motionEvent.getActionButton(), flags,
4695 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004696 motionEvent.getButtonState(),
4697 motionEvent.getClassification(),
4698 motionEvent.getEdgeFlags(),
4699 motionEvent.getXPrecision(),
4700 motionEvent.getYPrecision(),
4701 motionEvent.getRawXCursorPosition(),
4702 motionEvent.getRawYCursorPosition(),
4703 motionEvent.getDownTime(),
Siarhei Vishniakou6773db62023-04-21 11:30:20 -07004704 motionEvent.getPointerCount(),
4705 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004706 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004707 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4708 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004709 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004710 }
4711 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004714 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004715 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 }
4718
Prabir Pradhan5735a322022-04-11 17:23:34 +00004719 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004720 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 injectionState->injectionIsAsync = true;
4722 }
4723
4724 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004725 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004728 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004729 if (DEBUG_INJECTION) {
4730 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4731 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004732 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004733 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 }
4735
4736 mLock.unlock();
4737
4738 if (needWake) {
4739 mLooper->wake();
4740 }
4741
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004742 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004744 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004746 if (syncMode == InputEventInjectionSync::NONE) {
4747 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 } else {
4749 for (;;) {
4750 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004751 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 break;
4753 }
4754
4755 nsecs_t remainingTimeout = endTime - now();
4756 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004757 if (DEBUG_INJECTION) {
4758 ALOGD("injectInputEvent - Timed out waiting for injection result "
4759 "to become available.");
4760 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004761 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 break;
4763 }
4764
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004765 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 }
4767
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004768 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4769 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004771 if (DEBUG_INJECTION) {
4772 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4773 injectionState->pendingForegroundDispatches);
4774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 nsecs_t remainingTimeout = endTime - now();
4776 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004777 if (DEBUG_INJECTION) {
4778 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4779 "dispatches to finish.");
4780 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004781 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 break;
4783 }
4784
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004785 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 }
4787 }
4788 }
4789
4790 injectionState->release();
4791 } // release lock
4792
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004793 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004794 LOG(DEBUG) << "injectInputEvent - Finished with result "
4795 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797
4798 return injectionResult;
4799}
4800
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004801std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004802 std::array<uint8_t, 32> calculatedHmac;
4803 std::unique_ptr<VerifiedInputEvent> result;
4804 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004805 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004806 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4807 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4808 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004809 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004810 break;
4811 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004812 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004813 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4814 VerifiedMotionEvent verifiedMotionEvent =
4815 verifiedMotionEventFromMotionEvent(motionEvent);
4816 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004817 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004818 break;
4819 }
4820 default: {
4821 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4822 return nullptr;
4823 }
4824 }
4825 if (calculatedHmac == INVALID_HMAC) {
4826 return nullptr;
4827 }
tyiu1573a672023-02-21 22:38:32 +00004828 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004829 return nullptr;
4830 }
4831 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004832}
4833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004834void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004835 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004836 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004838 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004839 LOG(DEBUG) << "Setting input event injection result to "
4840 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004843 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 // Log the outcome since the injector did not wait for the injection result.
4845 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 ALOGV("Asynchronous input event injection succeeded.");
4848 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004849 case InputEventInjectionResult::TARGET_MISMATCH:
4850 ALOGV("Asynchronous input event injection target mismatch.");
4851 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004853 ALOGW("Asynchronous input event injection failed.");
4854 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004855 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004856 ALOGW("Asynchronous input event injection timed out.");
4857 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004858 case InputEventInjectionResult::PENDING:
4859 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4860 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
4862 }
4863
4864 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004865 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
4867}
4868
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004869void InputDispatcher::transformMotionEntryForInjectionLocked(
4870 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004871 // Input injection works in the logical display coordinate space, but the input pipeline works
4872 // display space, so we need to transform the injected events accordingly.
4873 const auto it = mDisplayInfos.find(entry.displayId);
4874 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004875 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004876
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004877 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4878 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4879 const vec2 cursor =
4880 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4881 {entry.xCursorPosition, entry.yCursorPosition});
4882 entry.xCursorPosition = cursor.x;
4883 entry.yCursorPosition = cursor.y;
4884 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004885 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004886 entry.pointerCoords[i] =
4887 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4888 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004889 }
4890}
4891
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004892void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4893 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 if (injectionState) {
4895 injectionState->pendingForegroundDispatches += 1;
4896 }
4897}
4898
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004899void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4900 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 if (injectionState) {
4902 injectionState->pendingForegroundDispatches -= 1;
4903
4904 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004905 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 }
4907 }
4908}
4909
chaviw98318de2021-05-19 16:45:23 -05004910const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004911 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004912 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004913 auto it = mWindowHandlesByDisplay.find(displayId);
4914 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004915}
4916
chaviw98318de2021-05-19 16:45:23 -05004917sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004918 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004919 if (windowHandleToken == nullptr) {
4920 return nullptr;
4921 }
4922
Arthur Hungb92218b2018-08-14 12:00:21 +08004923 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004924 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4925 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004926 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004927 return windowHandle;
4928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
4930 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004931 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932}
4933
chaviw98318de2021-05-19 16:45:23 -05004934sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4935 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004936 if (windowHandleToken == nullptr) {
4937 return nullptr;
4938 }
4939
chaviw98318de2021-05-19 16:45:23 -05004940 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004941 if (windowHandle->getToken() == windowHandleToken) {
4942 return windowHandle;
4943 }
4944 }
4945 return nullptr;
4946}
4947
chaviw98318de2021-05-19 16:45:23 -05004948sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4949 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004950 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004951 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4952 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004953 if (handle->getId() == windowHandle->getId() &&
4954 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004955 if (windowHandle->getInfo()->displayId != it.first) {
4956 ALOGE("Found window %s in display %" PRId32
4957 ", but it should belong to display %" PRId32,
4958 windowHandle->getName().c_str(), it.first,
4959 windowHandle->getInfo()->displayId);
4960 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004961 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 }
4964 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004965 return nullptr;
4966}
4967
chaviw98318de2021-05-19 16:45:23 -05004968sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004969 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4970 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971}
4972
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004973ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4974 auto displayInfoIt = mDisplayInfos.find(displayId);
4975 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4976 : kIdentityTransform;
4977}
4978
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004979bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4980 const MotionEntry& motionEntry) const {
4981 const WindowInfo& info = *window->getInfo();
4982
4983 // Skip spy window targets that are not valid for targeted injection.
4984 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004985 return false;
4986 }
4987
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004988 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4989 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4990 return false;
4991 }
4992
4993 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4994 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4995 window->getName().c_str());
4996 return false;
4997 }
4998
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004999 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005000 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005001 ALOGW("Not sending touch to %s because there's no corresponding connection",
5002 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005003 return false;
5004 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005005
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005006 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005007 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005008 return false;
5009 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005010
5011 // Drop events that can't be trusted due to occlusion
5012 const auto [x, y] = resolveTouchedPosition(motionEntry);
5013 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5014 if (!isTouchTrustedLocked(occlusionInfo)) {
5015 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005016 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005017 for (const auto& log : occlusionInfo.debugInfo) {
5018 ALOGD("%s", log.c_str());
5019 }
5020 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005021 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5022 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005023 return false;
5024 }
5025
5026 // Drop touch events if requested by input feature
5027 if (shouldDropInput(motionEntry, window)) {
5028 return false;
5029 }
5030
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005031 return true;
5032}
5033
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005034std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5035 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005036 auto connectionIt = mConnectionsByToken.find(token);
5037 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005038 return nullptr;
5039 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005040 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005041}
5042
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005043void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005044 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5045 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005046 // Remove all handles on a display if there are no windows left.
5047 mWindowHandlesByDisplay.erase(displayId);
5048 return;
5049 }
5050
5051 // Since we compare the pointer of input window handles across window updates, we need
5052 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005053 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5054 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5055 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005056 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005057 }
5058
chaviw98318de2021-05-19 16:45:23 -05005059 std::vector<sp<WindowInfoHandle>> newHandles;
5060 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005061 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005062 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005063 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005064 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005065 const bool canReceiveInput =
5066 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5067 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005068 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005069 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005070 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005071 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005072 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005073 }
5074
5075 if (info->displayId != displayId) {
5076 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5077 handle->getName().c_str(), displayId, info->displayId);
5078 continue;
5079 }
5080
Robert Carredd13602020-04-13 17:24:34 -07005081 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5082 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005083 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005084 oldHandle->updateFrom(handle);
5085 newHandles.push_back(oldHandle);
5086 } else {
5087 newHandles.push_back(handle);
5088 }
5089 }
5090
5091 // Insert or replace
5092 mWindowHandlesByDisplay[displayId] = newHandles;
5093}
5094
Arthur Hung72d8dc32020-03-28 00:48:39 +00005095void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05005096 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005097 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00005098 { // acquire lock
5099 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10005100 for (const auto& [displayId, handles] : handlesPerDisplay) {
5101 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005102 }
5103 }
5104 // Wake up poll loop since it may need to make new input dispatching choices.
5105 mLooper->wake();
5106}
5107
Arthur Hungb92218b2018-08-14 12:00:21 +08005108/**
5109 * Called from InputManagerService, update window handle list by displayId that can receive input.
5110 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5111 * If set an empty list, remove all handles from the specific display.
5112 * For focused handle, check if need to change and send a cancel event to previous one.
5113 * For removed handle, check if need to send a cancel event if already in touch.
5114 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005115void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005116 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005117 if (DEBUG_FOCUS) {
5118 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005119 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005120 windowList += iwh->getName() + " ";
5121 }
5122 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
Prabir Pradhand65552b2021-10-07 11:23:50 -07005125 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005126 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005127 const WindowInfo& info = *window->getInfo();
5128
5129 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005130 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005131 if (noInputWindow && window->getToken() != nullptr) {
5132 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5133 window->getName().c_str());
5134 window->releaseChannel();
5135 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005136
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005137 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005138 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5139 !info.inputConfig.test(
5140 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005141 "%s has feature SPY, but is not a trusted overlay.",
5142 window->getName().c_str());
5143
Prabir Pradhand65552b2021-10-07 11:23:50 -07005144 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005145 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5146 !info.inputConfig.test(
5147 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005148 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5149 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005150 }
5151
Arthur Hung72d8dc32020-03-28 00:48:39 +00005152 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005153 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005155 // Save the old windows' orientation by ID before it gets updated.
5156 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05005157 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005158 oldWindowOrientations.emplace(handle->getId(),
5159 handle->getInfo()->transform.getOrientation());
5160 }
5161
chaviw98318de2021-05-19 16:45:23 -05005162 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005163
chaviw98318de2021-05-19 16:45:23 -05005164 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005165
Vishnu Nairc519ff72021-01-21 08:23:08 -08005166 std::optional<FocusResolver::FocusChanges> changes =
5167 mFocusResolver.setInputWindows(displayId, windowHandles);
5168 if (changes) {
5169 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005172 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5173 mTouchStatesByDisplay.find(displayId);
5174 if (stateIt != mTouchStatesByDisplay.end()) {
5175 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005176 for (size_t i = 0; i < state.windows.size();) {
5177 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005178 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005179 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005180 ALOGD("Touched window was removed: %s in display %" PRId32,
5181 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005182 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005183 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005184 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5185 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005186 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005187 "touched window was removed");
5188 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005189 // Since we are about to drop the touch, cancel the events for the wallpaper as
5190 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005191 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005192 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5193 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005194 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005195 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005198 state.windows.erase(state.windows.begin() + i);
5199 } else {
5200 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201 }
5202 }
arthurhungb89ccb02020-12-30 16:19:01 +08005203
arthurhung6d4bed92021-03-17 11:59:33 +08005204 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005205 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005206 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005207 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005208 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005209 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5210 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005211 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005212 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005213 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005214
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005215 // Determine if the orientation of any of the input windows have changed, and cancel all
5216 // pointer events if necessary.
5217 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5218 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5219 if (newWindowHandle != nullptr &&
5220 newWindowHandle->getInfo()->transform.getOrientation() !=
5221 oldWindowOrientations[oldWindowHandle->getId()]) {
5222 std::shared_ptr<InputChannel> inputChannel =
5223 getInputChannelLocked(newWindowHandle->getToken());
5224 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005225 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005226 "touched window's orientation changed");
5227 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005228 }
5229 }
5230 }
5231
Arthur Hung72d8dc32020-03-28 00:48:39 +00005232 // Release information for windows that are no longer present.
5233 // This ensures that unused input channels are released promptly.
5234 // Otherwise, they might stick around until the window handle is destroyed
5235 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005236 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005237 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005238 if (DEBUG_FOCUS) {
5239 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005240 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005241 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005242 }
chaviw291d88a2019-02-14 10:33:58 -08005243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244}
5245
5246void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005247 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005248 if (DEBUG_FOCUS) {
5249 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5250 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5251 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005252 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005253 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005254 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 } // release lock
5256
5257 // Wake up poll loop since it may need to make new input dispatching choices.
5258 mLooper->wake();
5259}
5260
Vishnu Nair599f1412021-06-21 10:39:58 -07005261void InputDispatcher::setFocusedApplicationLocked(
5262 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5263 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5264 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5265
5266 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5267 return; // This application is already focused. No need to wake up or change anything.
5268 }
5269
5270 // Set the new application handle.
5271 if (inputApplicationHandle != nullptr) {
5272 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5273 } else {
5274 mFocusedApplicationHandlesByDisplay.erase(displayId);
5275 }
5276
5277 // No matter what the old focused application was, stop waiting on it because it is
5278 // no longer focused.
5279 resetNoFocusedWindowTimeoutLocked();
5280}
5281
Tiger Huang721e26f2018-07-24 22:26:19 +08005282/**
5283 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5284 * the display not specified.
5285 *
5286 * We track any unreleased events for each window. If a window loses the ability to receive the
5287 * released event, we will send a cancel event to it. So when the focused display is changed, we
5288 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5289 * display. The display-specified events won't be affected.
5290 */
5291void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005292 if (DEBUG_FOCUS) {
5293 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5294 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005295 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005296 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005297
5298 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005299 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005300 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005301 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005302 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005303 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005304 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005305 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005306 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005307 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005308 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005309 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5310 }
5311 }
5312 mFocusedDisplayId = displayId;
5313
Chris Ye3c2d6f52020-08-09 10:39:48 -07005314 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005315 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005316 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005317
Vishnu Nairad321cd2020-08-20 16:40:21 -07005318 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005319 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005320 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005321 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005322 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005323 }
5324 }
5325 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005326 } // release lock
5327
5328 // Wake up poll loop since it may need to make new input dispatching choices.
5329 mLooper->wake();
5330}
5331
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005333 if (DEBUG_FOCUS) {
5334 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336
5337 bool changed;
5338 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005339 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340
5341 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5342 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005343 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 }
5345
5346 if (mDispatchEnabled && !enabled) {
5347 resetAndDropEverythingLocked("dispatcher is being disabled");
5348 }
5349
5350 mDispatchEnabled = enabled;
5351 mDispatchFrozen = frozen;
5352 changed = true;
5353 } else {
5354 changed = false;
5355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356 } // release lock
5357
5358 if (changed) {
5359 // Wake up poll loop since it may need to make new input dispatching choices.
5360 mLooper->wake();
5361 }
5362}
5363
5364void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005365 if (DEBUG_FOCUS) {
5366 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368
5369 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005370 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371
5372 if (mInputFilterEnabled == enabled) {
5373 return;
5374 }
5375
5376 mInputFilterEnabled = enabled;
5377 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5378 } // release lock
5379
5380 // Wake up poll loop since there might be work to do to drop everything.
5381 mLooper->wake();
5382}
5383
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005384bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005385 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005386 bool needWake = false;
5387 {
5388 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005389 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005390 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005391 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005392 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5393 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005394 mTouchModePerDisplay.count(displayId) == 0
5395 ? "not set"
5396 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5397
Antonio Kantek15beb512022-06-13 22:35:41 +00005398 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5399 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005400 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005401 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005402 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005403 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5404 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005405 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005406 "window nor none of the previously interacted window",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005407 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005408 return false;
5409 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005410 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005411 mTouchModePerDisplay[displayId] = inTouchMode;
5412 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5413 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005414 needWake = enqueueInboundEventLocked(std::move(entry));
5415 } // release lock
5416
5417 if (needWake) {
5418 mLooper->wake();
5419 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005420 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005421}
5422
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005423bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005424 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5425 if (focusedToken == nullptr) {
5426 return false;
5427 }
5428 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5429 return isWindowOwnedBy(windowHandle, pid, uid);
5430}
5431
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005432bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005433 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5434 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5435 const sp<WindowInfoHandle> windowHandle =
5436 getWindowHandleLocked(connectionToken);
5437 return isWindowOwnedBy(windowHandle, pid, uid);
5438 }) != mInteractionConnectionTokens.end();
5439}
5440
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005441void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5442 if (opacity < 0 || opacity > 1) {
5443 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5444 return;
5445 }
5446
5447 std::scoped_lock lock(mLock);
5448 mMaximumObscuringOpacityForTouch = opacity;
5449}
5450
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005451std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5452InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005453 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5454 for (TouchedWindow& w : state.windows) {
5455 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005456 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005457 }
5458 }
5459 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005460 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005461}
5462
arthurhungb89ccb02020-12-30 16:19:01 +08005463bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5464 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005465 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005466 if (DEBUG_FOCUS) {
5467 ALOGD("Trivial transfer to same window.");
5468 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005469 return true;
5470 }
5471
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005473 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474
Arthur Hungabbb9d82021-09-01 14:52:30 +00005475 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005476 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005477
Arthur Hungabbb9d82021-09-01 14:52:30 +00005478 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005479 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 return false;
5481 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005482 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5483 if (deviceIds.size() != 1) {
5484 LOG(DEBUG) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5485 << " for window: " << touchedWindow->dump();
5486 return false;
5487 }
5488 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005489
Arthur Hungabbb9d82021-09-01 14:52:30 +00005490 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5491 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005492 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005493 return false;
5494 }
5495
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005496 if (DEBUG_FOCUS) {
5497 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005498 touchedWindow->windowHandle->getName().c_str(),
5499 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500 }
5501
Arthur Hungabbb9d82021-09-01 14:52:30 +00005502 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005503 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005504 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005505 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005506 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507
Arthur Hungabbb9d82021-09-01 14:52:30 +00005508 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005509 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005510 ftl::Flags<InputTarget::Flags> newTargetFlags =
5511 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005512 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005513 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005514 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005515 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5516 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517
Arthur Hungabbb9d82021-09-01 14:52:30 +00005518 // Store the dragging window.
5519 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005520 if (pointerIds.count() != 1) {
5521 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5522 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005523 return false;
5524 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005525 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005526 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005527 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 }
5529
Arthur Hungabbb9d82021-09-01 14:52:30 +00005530 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005531 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5532 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005533 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005534 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005535 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5536 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005538 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5539 newTargetFlags);
5540
5541 // Check if the wallpaper window should deliver the corresponding event.
5542 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005543 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 } // release lock
5546
5547 // Wake up poll loop since it may need to make new input dispatching choices.
5548 mLooper->wake();
5549 return true;
5550}
5551
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005552/**
5553 * Get the touched foreground window on the given display.
5554 * Return null if there are no windows touched on that display, or if more than one foreground
5555 * window is being touched.
5556 */
5557sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5558 auto stateIt = mTouchStatesByDisplay.find(displayId);
5559 if (stateIt == mTouchStatesByDisplay.end()) {
5560 ALOGI("No touch state on display %" PRId32, displayId);
5561 return nullptr;
5562 }
5563
5564 const TouchState& state = stateIt->second;
5565 sp<WindowInfoHandle> touchedForegroundWindow;
5566 // If multiple foreground windows are touched, return nullptr
5567 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005568 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005569 if (touchedForegroundWindow != nullptr) {
5570 ALOGI("Two or more foreground windows: %s and %s",
5571 touchedForegroundWindow->getName().c_str(),
5572 window.windowHandle->getName().c_str());
5573 return nullptr;
5574 }
5575 touchedForegroundWindow = window.windowHandle;
5576 }
5577 }
5578 return touchedForegroundWindow;
5579}
5580
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005581// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005582bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005583 sp<IBinder> fromToken;
5584 { // acquire lock
5585 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005586 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005587 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005588 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5589 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005590 return false;
5591 }
5592
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005593 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5594 if (from == nullptr) {
5595 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5596 return false;
5597 }
5598
5599 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005600 } // release lock
5601
5602 return transferTouchFocus(fromToken, destChannelToken);
5603}
5604
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005606 if (DEBUG_FOCUS) {
5607 ALOGD("Resetting and dropping all events (%s).", reason);
5608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609
Michael Wrightfb04fd52022-11-24 22:31:11 +00005610 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 synthesizeCancelationEventsForAllConnectionsLocked(options);
5612
5613 resetKeyRepeatLocked();
5614 releasePendingEventLocked();
5615 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005616 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005618 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005619 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005620 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621}
5622
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005623void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005624 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 dumpDispatchStateLocked(dump);
5626
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005627 std::istringstream stream(dump);
5628 std::string line;
5629
5630 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005631 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 }
5633}
5634
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005635std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005636 std::string dump;
5637
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005638 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5639 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005640
5641 std::string windowName = "None";
5642 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005643 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005644 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5645 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5646 : "token has capture without window";
5647 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005648 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005649
5650 return dump;
5651}
5652
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005653void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005654 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5655 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5656 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005657 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658
Tiger Huang721e26f2018-07-24 22:26:19 +08005659 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5660 dump += StringPrintf(INDENT "FocusedApplications:\n");
5661 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5662 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005663 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005664 const std::chrono::duration timeout =
5665 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005666 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005667 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005668 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005671 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005673
Vishnu Nairc519ff72021-01-21 08:23:08 -08005674 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005675 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005677 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005678 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005679 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005680 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5681 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 }
5683 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005684 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 }
5686
arthurhung6d4bed92021-03-17 11:59:33 +08005687 if (mDragState) {
5688 dump += StringPrintf(INDENT "DragState:\n");
5689 mDragState->dump(dump, INDENT2);
5690 }
5691
Arthur Hungb92218b2018-08-14 12:00:21 +08005692 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005693 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5694 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5695 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5696 const auto& displayInfo = it->second;
5697 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5698 displayInfo.logicalHeight);
5699 displayInfo.transform.dump(dump, "transform", INDENT4);
5700 } else {
5701 dump += INDENT2 "No DisplayInfo found!\n";
5702 }
5703
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005704 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005705 dump += INDENT2 "Windows:\n";
5706 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005707 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5708 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005710 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005711 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005712 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005713 "applicationInfo.name=%s, "
5714 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005715 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005716 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005717 windowInfo->displayId,
5718 windowInfo->inputConfig.string().c_str(),
5719 windowInfo->alpha, windowInfo->frameLeft,
5720 windowInfo->frameTop, windowInfo->frameRight,
5721 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005722 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005723 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005724 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005725 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005726 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005727 "touchOcclusionMode=%s\n",
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005728 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005729 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005730 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005731 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005732 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005733 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005734 }
5735 } else {
5736 dump += INDENT2 "Windows: <none>\n";
5737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005740 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
5742
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005743 if (!mGlobalMonitorsByDisplay.empty()) {
5744 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5745 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005746 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005749 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750 }
5751
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005752 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753
5754 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005755 if (!mRecentQueue.empty()) {
5756 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005757 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005758 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005759 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005760 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761 }
5762 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005763 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 }
5765
5766 // Dump event currently being dispatched.
5767 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005768 dump += INDENT "PendingEvent:\n";
5769 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005770 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005771 dump += StringPrintf(", age=%" PRId64 "ms\n",
5772 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005774 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 }
5776
5777 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005778 if (!mInboundQueue.empty()) {
5779 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005780 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005782 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005783 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 }
5785 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 }
5788
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005789 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005790 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005791 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005792 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005793 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005794 }
5795 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005796 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005797 }
5798
Prabir Pradhancef936d2021-07-21 16:17:52 +00005799 if (!mCommandQueue.empty()) {
5800 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5801 } else {
5802 dump += INDENT "CommandQueue: <empty>\n";
5803 }
5804
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005805 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005806 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005807 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005808 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005809 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005810 connection->inputChannel->getFd().get(),
5811 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005812 connection->getWindowName().c_str(),
5813 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005814 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005816 if (!connection->outboundQueue.empty()) {
5817 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5818 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005819 dump += dumpQueue(connection->outboundQueue, currentTime);
5820
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005822 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 }
5824
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005825 if (!connection->waitQueue.empty()) {
5826 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5827 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005828 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005830 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 }
5832 }
5833 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005834 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835 }
5836
5837 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005838 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5839 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005841 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 }
5843
Antonio Kantek15beb512022-06-13 22:35:41 +00005844 if (!mTouchModePerDisplay.empty()) {
5845 dump += INDENT "TouchModePerDisplay:\n";
5846 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5847 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5848 std::to_string(touchMode).c_str());
5849 }
5850 } else {
5851 dump += INDENT "TouchModePerDisplay: <none>\n";
5852 }
5853
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005854 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005855 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5856 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5857 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005858 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005859 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860}
5861
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005862void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005863 const size_t numMonitors = monitors.size();
5864 for (size_t i = 0; i < numMonitors; i++) {
5865 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005866 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005867 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5868 dump += "\n";
5869 }
5870}
5871
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005872class LooperEventCallback : public LooperCallback {
5873public:
5874 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5875 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5876
5877private:
5878 std::function<int(int events)> mCallback;
5879};
5880
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005881Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005882 if (DEBUG_CHANNEL_CREATION) {
5883 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005886 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005887 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005888 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005889
5890 if (result) {
5891 return base::Error(result) << "Failed to open input channel pair with name " << name;
5892 }
5893
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005895 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005896 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005897 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005898 std::shared_ptr<Connection> connection =
5899 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5900 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005902 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5903 ALOGE("Created a new connection, but the token %p is already known", token.get());
5904 }
5905 mConnectionsByToken.emplace(token, connection);
5906
5907 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5908 this, std::placeholders::_1, token);
5909
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005910 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005911 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 } // release lock
5913
5914 // Wake the looper because some connections have changed.
5915 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005916 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917}
5918
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005919Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005920 const std::string& name,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00005921 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005922 std::shared_ptr<InputChannel> serverChannel;
5923 std::unique_ptr<InputChannel> clientChannel;
5924 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5925 if (result) {
5926 return base::Error(result) << "Failed to open input channel pair with name " << name;
5927 }
5928
Michael Wright3dd60e22019-03-27 22:06:44 +00005929 { // acquire lock
5930 std::scoped_lock _l(mLock);
5931
5932 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005933 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5934 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005935 }
5936
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005937 std::shared_ptr<Connection> connection =
5938 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005939 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005940 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005941
5942 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5943 ALOGE("Created a new connection, but the token %p is already known", token.get());
5944 }
5945 mConnectionsByToken.emplace(token, connection);
5946 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5947 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005948
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005949 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005950
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005951 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005952 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005953 }
Garfield Tan15601662020-09-22 15:32:38 -07005954
Michael Wright3dd60e22019-03-27 22:06:44 +00005955 // Wake the looper because some connections have changed.
5956 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005957 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005958}
5959
Garfield Tan15601662020-09-22 15:32:38 -07005960status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005962 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963
Harry Cutts33476232023-01-30 19:57:29 +00005964 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 if (status) {
5966 return status;
5967 }
5968 } // release lock
5969
5970 // Wake the poll loop because removing the connection may have changed the current
5971 // synchronization state.
5972 mLooper->wake();
5973 return OK;
5974}
5975
Garfield Tan15601662020-09-22 15:32:38 -07005976status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5977 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005978 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005979 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005980 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 return BAD_VALUE;
5982 }
5983
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005984 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005985
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005987 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988 }
5989
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005990 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005991
5992 nsecs_t currentTime = now();
5993 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5994
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005995 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005996 return OK;
5997}
5998
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005999void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006000 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6001 auto& [displayId, monitors] = *it;
6002 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6003 return monitor.inputChannel->getConnectionToken() == connectionToken;
6004 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006005
Michael Wright3dd60e22019-03-27 22:06:44 +00006006 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006007 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006008 } else {
6009 ++it;
6010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011 }
6012}
6013
Michael Wright3dd60e22019-03-27 22:06:44 +00006014status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006015 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006016 return pilferPointersLocked(token);
6017}
Michael Wright3dd60e22019-03-27 22:06:44 +00006018
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006019status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006020 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6021 if (!requestingChannel) {
6022 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
6023 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006024 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006025
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006026 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006027 if (statePtr == nullptr || windowPtr == nullptr) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006028 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
6029 " Ignoring.");
6030 return BAD_VALUE;
6031 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006032 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
6033 if (deviceIds.size() != 1) {
6034 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
6035 << " in window: " << windowPtr->dump();
6036 return BAD_VALUE;
6037 }
6038 const int32_t deviceId = *deviceIds.begin();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006039
6040 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006041 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006042 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00006043 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006044 "input channel stole pointer stream");
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006045 options.deviceId = deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006046 options.displayId = displayId;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006047 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
6048 options.pointerIds = pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006049 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006050 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006051 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006052 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006053 if (channel != nullptr && channel->getConnectionToken() != token) {
6054 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6055 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6056 canceledWindows += channel->getName();
6057 }
6058 }
6059 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6060 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
6061 canceledWindows.c_str());
6062
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006063 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006064 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006065 window.addPilferingPointers(deviceId, pointerIds);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006066
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006067 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006068 return OK;
6069}
6070
Prabir Pradhan99987712020-11-10 18:43:05 -08006071void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6072 { // acquire lock
6073 std::scoped_lock _l(mLock);
6074 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006075 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006076 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6077 windowHandle != nullptr ? windowHandle->getName().c_str()
6078 : "token without window");
6079 }
6080
Vishnu Nairc519ff72021-01-21 08:23:08 -08006081 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006082 if (focusedToken != windowToken) {
6083 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6084 enabled ? "enable" : "disable");
6085 return;
6086 }
6087
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006088 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006089 ALOGW("Ignoring request to %s Pointer Capture: "
6090 "window has %s requested pointer capture.",
6091 enabled ? "enable" : "disable", enabled ? "already" : "not");
6092 return;
6093 }
6094
Christine Franksb768bb42021-11-29 12:11:31 -08006095 if (enabled) {
6096 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6097 mIneligibleDisplaysForPointerCapture.end(),
6098 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6099 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6100 return;
6101 }
6102 }
6103
Prabir Pradhan99987712020-11-10 18:43:05 -08006104 setPointerCaptureLocked(enabled);
6105 } // release lock
6106
6107 // Wake the thread to process command entries.
6108 mLooper->wake();
6109}
6110
Christine Franksb768bb42021-11-29 12:11:31 -08006111void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6112 { // acquire lock
6113 std::scoped_lock _l(mLock);
6114 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6115 if (!isEligible) {
6116 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6117 }
6118 } // release lock
6119}
6120
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006121std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006122 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006123 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006124 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006125 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006126 }
6127 }
6128 }
6129 return std::nullopt;
6130}
6131
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006132std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6133 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006134 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006135 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006136 }
6137
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006138 for (const auto& [token, connection] : mConnectionsByToken) {
6139 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006140 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 }
6142 }
Robert Carr4e670e52018-08-15 13:26:12 -07006143
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006144 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145}
6146
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006147std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006148 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006149 if (connection == nullptr) {
6150 return "<nullptr>";
6151 }
6152 return connection->getInputChannelName();
6153}
6154
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006155void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006156 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006157 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006158}
6159
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006161 const std::shared_ptr<Connection>& connection,
6162 uint32_t seq, bool handled,
6163 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164 // Handle post-event policy actions.
6165 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
6166 if (dispatchEntryIt == connection->waitQueue.end()) {
6167 return;
6168 }
6169 DispatchEntry* dispatchEntry = *dispatchEntryIt;
6170 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
6171 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6172 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6173 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
6174 }
6175 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
6176 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
6177 connection->inputChannel->getConnectionToken(),
6178 dispatchEntry->deliveryTime, consumeTime, finishTime);
6179 }
6180
6181 bool restartEvent;
6182 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
6183 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
6184 restartEvent =
6185 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6186 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
6187 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
6188 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
6189 handled);
6190 } else {
6191 restartEvent = false;
6192 }
6193
6194 // Dequeue the event and start the next cycle.
6195 // Because the lock might have been released, it is possible that the
6196 // contents of the wait queue to have been drained, so we need to double-check
6197 // a few things.
6198 dispatchEntryIt = connection->findWaitQueueEntry(seq);
6199 if (dispatchEntryIt != connection->waitQueue.end()) {
6200 dispatchEntry = *dispatchEntryIt;
6201 connection->waitQueue.erase(dispatchEntryIt);
6202 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6203 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6204 if (!connection->responsive) {
6205 connection->responsive = isConnectionResponsive(*connection);
6206 if (connection->responsive) {
6207 // The connection was unresponsive, and now it's responsive.
6208 processConnectionResponsiveLocked(*connection);
6209 }
6210 }
6211 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006212 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006213 connection->outboundQueue.push_front(dispatchEntry);
6214 traceOutboundQueueLength(*connection);
6215 } else {
6216 releaseDispatchEntry(dispatchEntry);
6217 }
6218 }
6219
6220 // Start the next dispatch cycle for this connection.
6221 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222}
6223
Prabir Pradhancef936d2021-07-21 16:17:52 +00006224void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6225 const sp<IBinder>& newToken) {
6226 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6227 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006228 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229 };
6230 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231}
6232
Prabir Pradhancef936d2021-07-21 16:17:52 +00006233void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6234 auto command = [this, token, x, y]() REQUIRES(mLock) {
6235 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006236 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006237 };
6238 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006239}
6240
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006241void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006242 if (connection == nullptr) {
6243 LOG_ALWAYS_FATAL("Caller must check for nullness");
6244 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006245 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6246 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006247 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006248 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006249 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006250 return;
6251 }
6252 /**
6253 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6254 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6255 * has changed. This could cause newer entries to time out before the already dispatched
6256 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6257 * processes the events linearly. So providing information about the oldest entry seems to be
6258 * most useful.
6259 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006260 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006261 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6262 std::string reason =
6263 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006264 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006265 ns2ms(currentWait),
6266 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006267 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006268 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006269
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006270 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6271
6272 // Stop waking up for events on this connection, it is already unresponsive
6273 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006274}
6275
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006276void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6277 std::string reason =
6278 StringPrintf("%s does not have a focused window", application->getName().c_str());
6279 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006280
Yabin Cui8eb9c552023-06-08 18:05:07 +00006281 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006283 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284 };
6285 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006286}
6287
chaviw98318de2021-05-19 16:45:23 -05006288void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006289 const std::string& reason) {
6290 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6291 updateLastAnrStateLocked(windowLabel, reason);
6292}
6293
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006294void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6295 const std::string& reason) {
6296 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006297 updateLastAnrStateLocked(windowLabel, reason);
6298}
6299
6300void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6301 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006302 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006303 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006304 struct tm tm;
6305 localtime_r(&t, &tm);
6306 char timestr[64];
6307 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006308 mLastAnrState.clear();
6309 mLastAnrState += INDENT "ANR:\n";
6310 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006311 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6312 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006313 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314}
6315
Prabir Pradhancef936d2021-07-21 16:17:52 +00006316void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6317 KeyEntry& entry) {
6318 const KeyEvent event = createKeyEvent(entry);
6319 nsecs_t delay = 0;
6320 { // release lock
6321 scoped_unlock unlock(mLock);
6322 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006323 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006324 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6325 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6326 std::to_string(t.duration().count()).c_str());
6327 }
6328 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329
6330 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006331 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006332 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006333 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006335 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006336 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006338}
6339
Prabir Pradhancef936d2021-07-21 16:17:52 +00006340void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006341 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006342 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006343 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006344 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006345 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006346 };
6347 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348}
6349
Prabir Pradhanedd96402022-02-15 01:46:16 -08006350void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006351 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006352 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006353 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006354 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006355 };
6356 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006357}
6358
6359/**
6360 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6361 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6362 * command entry to the command queue.
6363 */
6364void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6365 std::string reason) {
6366 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006367 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006368 if (connection.monitor) {
6369 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6370 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006371 pid = findMonitorPidByTokenLocked(connectionToken);
6372 } else {
6373 // The connection is a window
6374 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6375 reason.c_str());
6376 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6377 if (handle != nullptr) {
6378 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006379 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006380 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006381 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006382}
6383
6384/**
6385 * Tell the policy that a connection has become responsive so that it can stop ANR.
6386 */
6387void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6388 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00006389 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006390 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006391 pid = findMonitorPidByTokenLocked(connectionToken);
6392 } else {
6393 // The connection is a window
6394 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6395 if (handle != nullptr) {
6396 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006397 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006398 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006399 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006400}
6401
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006402bool InputDispatcher::afterKeyEventLockedInterruptable(
6403 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6404 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006405 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006406 if (!handled) {
6407 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006408 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006409 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006410 return false;
6411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006413 // Get the fallback key state.
6414 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006415 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006416 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006417 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006418 connection->inputState.removeFallbackKey(originalKeyCode);
6419 }
6420
6421 if (handled || !dispatchEntry->hasForegroundTarget()) {
6422 // If the application handles the original key for which we previously
6423 // generated a fallback or if the window is not a foreground window,
6424 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006425 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006426 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006427 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6428 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6429 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6430 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6431 keyEntry.policyFlags);
6432 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006433 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006434 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435
6436 mLock.unlock();
6437
Prabir Pradhana41d2442023-04-20 21:30:40 +00006438 if (const auto unhandledKeyFallback =
6439 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6440 event, keyEntry.policyFlags);
6441 unhandledKeyFallback) {
6442 event = *unhandledKeyFallback;
6443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006444
6445 mLock.lock();
6446
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006447 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006448 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006449 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006450 "application handled the original non-fallback key "
6451 "or is no longer a foreground target, "
6452 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006453 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006454 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006455 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006456 connection->inputState.removeFallbackKey(originalKeyCode);
6457 }
6458 } else {
6459 // If the application did not handle a non-fallback key, first check
6460 // that we are in a good state to perform unhandled key event processing
6461 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006462 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006464 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6465 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6466 "since this is not an initial down. "
6467 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6468 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6469 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006470 return false;
6471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6475 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6476 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6477 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6478 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006479 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480
6481 mLock.unlock();
6482
Prabir Pradhana41d2442023-04-20 21:30:40 +00006483 bool fallback = false;
6484 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6485 event, keyEntry.policyFlags);
6486 fb) {
6487 fallback = true;
6488 event = *fb;
6489 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490
6491 mLock.lock();
6492
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006493 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006494 connection->inputState.removeFallbackKey(originalKeyCode);
6495 return false;
6496 }
6497
6498 // Latch the fallback keycode for this key on an initial down.
6499 // The fallback keycode cannot change at any other point in the lifecycle.
6500 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006502 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006504 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006505 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006507 }
6508
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006509 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006510
6511 // Cancel the fallback key if the policy decides not to send it anymore.
6512 // We will continue to dispatch the key to the policy but we will no
6513 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006514 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6515 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006516 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6517 if (fallback) {
6518 ALOGD("Unhandled key event: Policy requested to send key %d"
6519 "as a fallback for %d, but on the DOWN it had requested "
6520 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006521 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006522 } else {
6523 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6524 "but on the DOWN it had requested to send %d. "
6525 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006526 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006528 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006529
Michael Wrightfb04fd52022-11-24 22:31:11 +00006530 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006531 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006532 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533 synthesizeCancelationEventsForConnectionLocked(connection, options);
6534
6535 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006536 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006537 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006538 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006539 }
6540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006542 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6543 {
6544 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006545 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006546 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006547 for (const auto& [key, value] : fallbackKeys) {
6548 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006549 }
6550 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6551 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006553 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006554
6555 if (fallback) {
6556 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006557 keyEntry.eventTime = event.getEventTime();
6558 keyEntry.deviceId = event.getDeviceId();
6559 keyEntry.source = event.getSource();
6560 keyEntry.displayId = event.getDisplayId();
6561 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006562 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006563 keyEntry.scanCode = event.getScanCode();
6564 keyEntry.metaState = event.getMetaState();
6565 keyEntry.repeatCount = event.getRepeatCount();
6566 keyEntry.downTime = event.getDownTime();
6567 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006568
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006569 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6570 ALOGD("Unhandled key event: Dispatching fallback key. "
6571 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006572 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006573 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006574 return true; // restart the event
6575 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006576 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6577 ALOGD("Unhandled key event: No fallback key.");
6578 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006579
6580 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006581 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582 }
6583 }
6584 return false;
6585}
6586
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006587bool InputDispatcher::afterMotionEventLockedInterruptable(
6588 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6589 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590 return false;
6591}
6592
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593void InputDispatcher::traceInboundQueueLengthLocked() {
6594 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006595 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006596 }
6597}
6598
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006599void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006600 if (ATRACE_ENABLED()) {
6601 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006602 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6603 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 }
6605}
6606
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006607void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608 if (ATRACE_ENABLED()) {
6609 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006610 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6611 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006612 }
6613}
6614
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006615void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006616 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006618 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619 dumpDispatchStateLocked(dump);
6620
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006621 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006622 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006623 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624 }
6625}
6626
6627void InputDispatcher::monitor() {
6628 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006629 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006631 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632}
6633
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006634/**
6635 * Wake up the dispatcher and wait until it processes all events and commands.
6636 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6637 * this method can be safely called from any thread, as long as you've ensured that
6638 * the work you are interested in completing has already been queued.
6639 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006640bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006641 /**
6642 * Timeout should represent the longest possible time that a device might spend processing
6643 * events and commands.
6644 */
6645 constexpr std::chrono::duration TIMEOUT = 100ms;
6646 std::unique_lock lock(mLock);
6647 mLooper->wake();
6648 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6649 return result == std::cv_status::no_timeout;
6650}
6651
Vishnu Naire798b472020-07-23 13:52:21 -07006652/**
6653 * Sets focus to the window identified by the token. This must be called
6654 * after updating any input window handles.
6655 *
6656 * Params:
6657 * request.token - input channel token used to identify the window that should gain focus.
6658 * request.focusedToken - the token that the caller expects currently to be focused. If the
6659 * specified token does not match the currently focused window, this request will be dropped.
6660 * If the specified focused token matches the currently focused window, the call will succeed.
6661 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6662 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6663 * when requesting the focus change. This determines which request gets
6664 * precedence if there is a focus change request from another source such as pointer down.
6665 */
Vishnu Nair958da932020-08-21 17:12:37 -07006666void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6667 { // acquire lock
6668 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006669 std::optional<FocusResolver::FocusChanges> changes =
6670 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6671 if (changes) {
6672 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006673 }
6674 } // release lock
6675 // Wake up poll loop since it may need to make new input dispatching choices.
6676 mLooper->wake();
6677}
6678
Vishnu Nairc519ff72021-01-21 08:23:08 -08006679void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6680 if (changes.oldFocus) {
6681 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006682 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006683 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006684 "focus left window");
6685 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006686 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006687 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006688 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006689 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006690 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006691 }
6692
Prabir Pradhan99987712020-11-10 18:43:05 -08006693 // If a window has pointer capture, then it must have focus. We need to ensure that this
6694 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6695 // If the window loses focus before it loses pointer capture, then the window can be in a state
6696 // where it has pointer capture but not focus, violating the contract. Therefore we must
6697 // dispatch the pointer capture event before the focus event. Since focus events are added to
6698 // the front of the queue (above), we add the pointer capture event to the front of the queue
6699 // after the focus events are added. This ensures the pointer capture event ends up at the
6700 // front.
6701 disablePointerCaptureForcedLocked();
6702
Vishnu Nairc519ff72021-01-21 08:23:08 -08006703 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006704 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006705 }
6706}
Vishnu Nair958da932020-08-21 17:12:37 -07006707
Prabir Pradhan99987712020-11-10 18:43:05 -08006708void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006709 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006710 return;
6711 }
6712
6713 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6714
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006715 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006716 setPointerCaptureLocked(false);
6717 }
6718
6719 if (!mWindowTokenWithPointerCapture) {
6720 // No need to send capture changes because no window has capture.
6721 return;
6722 }
6723
6724 if (mPendingEvent != nullptr) {
6725 // Move the pending event to the front of the queue. This will give the chance
6726 // for the pending event to be dropped if it is a captured event.
6727 mInboundQueue.push_front(mPendingEvent);
6728 mPendingEvent = nullptr;
6729 }
6730
6731 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006732 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006733 mInboundQueue.push_front(std::move(entry));
6734}
6735
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006736void InputDispatcher::setPointerCaptureLocked(bool enable) {
6737 mCurrentPointerCaptureRequest.enable = enable;
6738 mCurrentPointerCaptureRequest.seq++;
6739 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006740 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006741 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006742 };
6743 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006744}
6745
Vishnu Nair599f1412021-06-21 10:39:58 -07006746void InputDispatcher::displayRemoved(int32_t displayId) {
6747 { // acquire lock
6748 std::scoped_lock _l(mLock);
6749 // Set an empty list to remove all handles from the specific display.
6750 setInputWindowsLocked(/* window handles */ {}, displayId);
6751 setFocusedApplicationLocked(displayId, nullptr);
6752 // Call focus resolver to clean up stale requests. This must be called after input windows
6753 // have been removed for the removed display.
6754 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006755 // Reset pointer capture eligibility, regardless of previous state.
6756 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006757 // Remove the associated touch mode state.
6758 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006759 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006760 } // release lock
6761
6762 // Wake up poll loop since it may need to make new input dispatching choices.
6763 mLooper->wake();
6764}
6765
Patrick Williamsd828f302023-04-28 17:52:08 -05006766void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006767 // The listener sends the windows as a flattened array. Separate the windows by display for
6768 // more convenient parsing.
6769 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006770 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006771 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006772 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006773 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006774
6775 { // acquire lock
6776 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006777
6778 // Ensure that we have an entry created for all existing displays so that if a displayId has
6779 // no windows, we can tell that the windows were removed from the display.
6780 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6781 handlesPerDisplay[displayId];
6782 }
6783
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006784 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006785 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006786 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6787 }
6788
6789 for (const auto& [displayId, handles] : handlesPerDisplay) {
6790 setInputWindowsLocked(handles, displayId);
6791 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006792
6793 if (update.vsyncId < mWindowInfosVsyncId) {
6794 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6795 ", current update vsync id: %" PRId64,
6796 mWindowInfosVsyncId, update.vsyncId);
6797 }
6798 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006799 }
6800 // Wake up poll loop since it may need to make new input dispatching choices.
6801 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006802}
6803
Vishnu Nair062a8672021-09-03 16:07:44 -07006804bool InputDispatcher::shouldDropInput(
6805 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006806 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6807 (windowHandle->getInfo()->inputConfig.test(
6808 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006809 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006810 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6811 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006812 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006813 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006814 windowHandle->getInfo()->displayId);
6815 return true;
6816 }
6817 return false;
6818}
6819
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006820void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006821 const gui::WindowInfosUpdate& update) {
6822 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006823}
6824
Arthur Hungdfd528e2021-12-08 13:23:04 +00006825void InputDispatcher::cancelCurrentTouch() {
6826 {
6827 std::scoped_lock _l(mLock);
6828 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006829 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006830 "cancel current touch");
6831 synthesizeCancelationEventsForAllConnectionsLocked(options);
6832
6833 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006834 }
6835 // Wake up poll loop since there might be work to do.
6836 mLooper->wake();
6837}
6838
Prabir Pradhan87112a72023-04-20 19:13:39 +00006839void InputDispatcher::requestRefreshConfiguration() {
Prabir Pradhana41d2442023-04-20 21:30:40 +00006840 InputDispatcherConfiguration config = mPolicy.getDispatcherConfiguration();
Prabir Pradhan87112a72023-04-20 19:13:39 +00006841
6842 std::scoped_lock _l(mLock);
6843 mConfig = config;
6844}
6845
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006846void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6847 std::scoped_lock _l(mLock);
6848 mMonitorDispatchingTimeout = timeout;
6849}
6850
Arthur Hungc539dbb2022-12-08 07:45:36 +00006851void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6852 const sp<WindowInfoHandle>& oldWindowHandle,
6853 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006854 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006855 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006856 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6857 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006858 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6859 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6860 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6861 newWindowHandle->getInfo()->inputConfig.test(
6862 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6863 const sp<WindowInfoHandle> oldWallpaper =
6864 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6865 const sp<WindowInfoHandle> newWallpaper =
6866 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6867 if (oldWallpaper == newWallpaper) {
6868 return;
6869 }
6870
6871 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006872 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6873 addWindowTargetLocked(oldWallpaper,
6874 oldTouchedWindow.targetFlags |
6875 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006876 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6877 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006878 }
6879
6880 if (newWallpaper != nullptr) {
6881 state.addOrUpdateWindow(newWallpaper,
6882 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6883 InputTarget::Flags::WINDOW_IS_OBSCURED |
6884 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006885 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006886 }
6887}
6888
6889void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6890 ftl::Flags<InputTarget::Flags> newTargetFlags,
6891 const sp<WindowInfoHandle> fromWindowHandle,
6892 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006893 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006894 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006895 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6896 fromWindowHandle->getInfo()->inputConfig.test(
6897 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6898 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6899 toWindowHandle->getInfo()->inputConfig.test(
6900 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6901
6902 const sp<WindowInfoHandle> oldWallpaper =
6903 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6904 const sp<WindowInfoHandle> newWallpaper =
6905 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6906 if (oldWallpaper == newWallpaper) {
6907 return;
6908 }
6909
6910 if (oldWallpaper != nullptr) {
6911 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6912 "transferring touch focus to another window");
6913 state.removeWindowByToken(oldWallpaper->getToken());
6914 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6915 }
6916
6917 if (newWallpaper != nullptr) {
6918 nsecs_t downTimeInTarget = now();
6919 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6920 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6921 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6922 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006923 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6924 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006925 std::shared_ptr<Connection> wallpaperConnection =
6926 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006927 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006928 std::shared_ptr<Connection> toConnection =
6929 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006930 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6931 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6932 wallpaperFlags);
6933 }
6934 }
6935}
6936
6937sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6938 const sp<WindowInfoHandle>& windowHandle) const {
6939 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6940 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6941 bool foundWindow = false;
6942 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6943 if (!foundWindow && otherHandle != windowHandle) {
6944 continue;
6945 }
6946 if (windowHandle == otherHandle) {
6947 foundWindow = true;
6948 continue;
6949 }
6950
6951 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6952 return otherHandle;
6953 }
6954 }
6955 return nullptr;
6956}
6957
Garfield Tane84e6f92019-08-29 17:28:41 -07006958} // namespace android::inputdispatcher